Posted By

pckujawa on 02/11/10


Tagged

socket tcp ethernet udp


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


Bind a socket (including UdpClient and TcpClient) to a local network interface card (NIC)


 / Published in: C#
 

If you are using a UdpClient or TcpClient, you have access to the internal Socket which either type uses. Unfortunately, if you try to Bind that Socket to a local Endpoint (IPAddress and Port), you will probably get a SocketException. The solution I found is to create the Socket independently, then assign that instance to the UdpClient (as shown in the code) or TcpClient (changing the Socket parameters, of course).

  1. using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  2. {
  3. var endPoint = new IPEndPoint(ip, port);
  4. socket.Bind(endPoint);
  5. using (var client = new UdpClient() {Client = socket})
  6. {
  7. var destinationIP = IPAddress.Broadcast;
  8. client.Connect(destinationIP, port);
  9. client.Send(bytes, bytes.Length);
  10. }
  11. }

Report this snippet  

You need to login to post a comment.