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?
The constructor must be called with the port and an optional encrypt pass phrase . It exposes a method called Send that allows you to broadcast a message to the LAN and a property called Received that maintains a queue of all the messages that have been broadcasted by any host in the LAN.
Unfortunately there is not a way to have the broadcast forwarded to every network. The closest that you can come would be to use a directed broadcast. To use this you would need a helper address for each subnet using the subnet broadcast address and you would also need a configuration statement on the router interface where that subnet was.
Direct broadcast - Sent to all hosts on a network. Routers may be configured to forward directed broadcasts on large networks. For network 192.168.0.0, the broadcast is 192.168.255.255. In this article we will build a library to perform Limited Broadcasts.
There are two types of Broadcast: Limited Broadcast - Sent to all NICs on the some network segment as the source NIC. It is represented with the 255.255.255.255 TCP/IP address. This broadcast is not forwarded by routers so will only appear on one network segment. Direct broadcast - Sent to all hosts on a network.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With