While working with sockets, I have found following piece of code:
using System.Net.Sockets;
...
private Socket _socket;
...
_socket.Blocking = false;
_socket.Bind(GetCurrentServerIpAddress());
_socket.BeginConnect(endpoint, OnConnect, _socket);
The result of the GetCurrentServerIpAddress()
is the IP address of the machine I need to connect to. As I don't understand what the Bind()
method does, I have removed it from the source code and I see no difference in behaviour: connections are created and repaired if needed, ..., so my question is very simple:
What does the _socket.Bind()
method do and what are the foreseen effects when I remove it?
Thanks in advance
The .NET docs have a rather vague explanation about it here.
Use the Bind method if you need to use a specific local endpoint. You must call Bind before you can call the Listen method. You do not need to call Bind before using the Connect method unless you need to use a specific local endpoint. You can use the Bind method on both connectionless and connection-oriented protocols.
Here they highlight that you don't need to bind the IP before connecting and it is only required if you want to call the listen()
method.
After searching for multiple examples on just the socket class I don't really see people implementing Bind()
. So unless you plan on using the Listen()
method I'd say its safe to remove it