Reputation: 36483
I need to create a socket which connects to a server process, but must be restricted to using a specified local adapter. The default behaviour is to use whatever it can, but I need to make sure that a given socket only tries (for example), the LAN connection, if both wifi and LAN are available.
I am using C# and .NET 2.0.
Cheers
Upvotes: 9
Views: 21906
Reputation: 16891
For the reference of others, I was having a problem using Bind because I was using the UdpClient class and accessing its internal Socket (via UdpClient.Client) which would throw a SocketException no matter how I tried to Bind. My workaround relies on creating and binding the Socket first, then assigning it to the UdpClient instance:
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
var endPoint = new IPEndPoint(ip, port);
socket.Bind(endPoint);
using (var client = new UdpClient() {Client = socket})
{
var destinationIP = IPAddress.Broadcast;
client.Connect(destinationIP, port);
client.Send(bytes, bytes.Length);
}
}
Upvotes: 7
Reputation: 25186
The Socket.Bind(EndPoint localEP)
method is your friend. Look here at MSDN for the details.
To get all local adapters and their type look at System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
Upvotes: 15
Reputation: 4880
could You try to use bind() function? Maybe this would do the trick.
On msdn I've found that:
(http://msdn.microsoft.com/en-us/library/ms737550(VS.85).aspx)
Remarks
The bind function is required on an unconnected socket before subsequent calls to the listen function. It is normally used to bind to either connection-oriented (stream) or connectionless (datagram) sockets. The bind function may also be used to bind to a raw socket (the socket was created by calling the socket function with the type parameter set to SOCK_RAW). The bind function may also be used on an unconnected socket before subsequent calls to the connect, ConnectEx, WSAConnect, WSAConnectByList, or WSAConnectByName functions before send operations.
When a socket is created with a call to the socket function, it exists in a namespace (address family), but it has no name assigned to it. Use the bind function to establish the local association of the socket by assigning a local name to an unnamed socket.
A name consists of three parts when using the Internet address family: The address family. A host address. A port number that identifies the application.
Upvotes: 0