I need to send a UDP message to specific IP and Port.
Since there are 3 network cards,
10.1.x.x
10.2.x.x
10.4.x.x
when i send a UDP message,i am receiving the message only in one network adapter...the rest of the ip's are not receiving.
I want to check for the network adapter while sending the message. How can I do that?
Currently I am using the following:
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse(LocalIP), 0);
IPEndPoint targetEndPoint = new IPEndPoint(TargetIP, iTargetPort);
UdpClient sendUdpClient = new UdpClient(localEndPoint);
int numBytesSent = sendUdpClient.Send(CombineHeaderBody, CombineHeaderBody.Length, targetEndPoint);
This is actually trickier than it sounds because if you have more than one interface the broadcasts will not always go out to all the interfaces. To get around this I created this class.
Then to send the UDP packet via broadcast, I use something like the following. I am using
IPAddress.Broadcast
andMyUdpClient
, which is different from your code.Also, you should note that when you use a specific
ipaddress
instead of broadcast the route table only sends it out the interface that matches the address.So in your example, unicast is used. You need to set
LocalIP
to the IP of the local interface you want to send out to. With three interfaces, you would have three local IP's and you need to pick the correct one to use.Because route is turned off you might see it on all interfaces but you will need to test this for the unicast case.
If you don't care about the send IP or port you can use the following code.
or for broadcast
The problem with
IPAddress.Broadcast
is that they will not route through any gateways. To get around this you can create a list ofIPAddresses
and then loop through and send. Also since Send can fail for network issues that you cannot control you should also have a try/catch block.Edit: see above change to unicast with multiple interfaces and also Problem Trying to unicast packets to available networks.
I solved this problem by sending the UDP broadcast from each adapter (using bind):
Expansion of Rex's Answer. This allows you to not have to hard code the ip addresses that you want to broadcast on. Loops through all interfaces, checks if they are up, makes sure it has IPv4 information, and an IPv4 address is associated with it. Just change the "data" variable to whatever data you want to broadcast, and the "target" port to the one you want. Small drawback is that if an interface has multiple ip addresses associated with it, it will broadcast out of each address. Note: this will ALSO try to send broadcasts through any VPN adapter (via Network and Sharing Center/Network Connections, Win 7+ verified), and if you want to receive responses, you will have to save all the clients. You also will not need a secondary class.
If you are sending to a specific IP address then you are unicasting, not broadcasting.