• C# socket broadcasts sent out on a random interface

    Today I was working on a service discovery algoritm using C# sockets sending and receiving broadcast packets. It worked fine when the computer in use is having just one network interface, but testing on a different machine, I found out that even while binding the socket to IPAddress.Any, it still picks just one of the interfaces to send out the packet.

    The solution is to use the ‘do not route’ option on the socket. The code becomes:

    sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
    string hostname = Dns.GetHostName();
    data = Encoding.ASCII.GetBytes(hostname);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, true);
    sock.Bind(new IPEndPoint(IPAddress.Any, 9051));
    sock.SendTo(data, iep1);