tags:

views:

1098

answers:

3

I have an application that sends broadcast messages and listens for response packets. Below is the code snippet.

m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);

m_socket.Bind(new IPEndPoint(IPAddress.Any, 2000));

m_socket.BeginSendTo(
                    buffer, 
                    0, 
                    buffer.Length, 
                    SocketFlags.None,
                    new IPEndPoint(IPAddress.Broadcast, 2000),
                    Callback), 
                    null
                    );

When I run the application the broadcast message was not being sent. On my machine I have three network adapters. One is my local network adapter and other two are VMWare network virtual adapters. When I run my application I can see (using wireshark network capture) that the broadcast message is being sent from one of the VMWare network adapters.

I would like to modify the code so that the broadcast message will be sent from all network adapters on the pc. What is the best way to do that?

+5  A: 

When you call Bind(), you are setting the local IP end point. Instead of using IPAddress.Any, use the IP address of the NIC that you want to send from. You'll need to do this separately for each NIC.

Jon B
+5  A: 

You can use the following to get all your IP Addresses (and a lot more). So you can iterate through the list and bind (like Jon B said) to the specific IP you want when you send out your multicast.

foreach (var i in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
    foreach (var ua in i.GetIPProperties().UnicastAddresses)
        Console.WriteLine(ua.Address);
JD Conley
+1 for iterating through the list of available NICs. :D
Dalin Seivewright
A: 

You can use IPAddress.Any when constructing the tcpListener. This will bind the tcp listener to all interfaces

Puscasu Razvan