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


/ Published in: C#
Save to your folder(s)

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).


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.