Return to Snippet

Revision: 23706
at February 11, 2010 13:41 by pckujawa

Initial Code
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    var endPoint = new IPEndPoint(ip, port);
    using (var client = new UdpClient() {Client = socket})
        var destinationIP = IPAddress.Broadcast;
        client.Connect(destinationIP, port);
        client.Send(bytes, bytes.Length);

Initial URL

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

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

Initial Tags

Initial Language