Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving UDP Broadcast message in C#

I know this question has been asked many times. I've read ALL the answers and tried EVRY piece of code I could find. After a few days I'm so desperate that I have to ask you for help.

I have a device and a PC in my home network. The device sends UDP broadcast messages. On my PC I can see those messages in wireshark:

Source Destination Length

192.168.1.102 0.0.0.0 UDP 60 Source port: 9050 Destination port: 0

That means the packets are arriving on my PC. My next step was to create a C# application that receives those packets. As mentioned above I tried every possible solution, but it just won't receive anything.

So I guess there must be something very basic I'm doing wrong. Can anyone help me out? Thanks!

like image 927
Boris Avatar asked Sep 25 '12 16:09

Boris


1 Answers

Just experienced the same issue, and wanted to share what fixed it for me.

Briefly: it seems that Windows Firewall was somehow the cause of this weird behavior, and just disabling the service does not help. You have to explicitly allow incoming UDP packets for specific program (executable) in Windows Firewall inbound rules list.

For full case description, read on.

My network setup is: IP of my (receiving) machine was 192.168.1.2, IP of sending machine was 192.168.1.50, and subnet mask on both machines was 255.255.255.0. My machine is running Windows 7 x64.

This is the code (roughly) that I used:

Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
sock.Bind(iep);
sock.EnableBroadcast = true;
EndPoint ep = (EndPoint)iep;
byte[] buffer = new byte[1000];
sock.ReceiveFrom(buffer, ref ep);

Initially this did not work unless I sent a broadcast packet from that socket before I call ReceiveFrom on it. I.e. adding this line before ReceiveFrom call:

sock.SendTo(someData, new IPEndPoint(IPAddress.Broadcast, somePort))

When I didn't send the broadcast packet first from receiving socket, incoming broadcast packets were not received by it, even though they appeared in Wireshark (destination of packets was 255.255.255.255).

I thought that it looks like firewall is messing with incoming packets (unless some kind of UDP hole is opened first by outgoing packet - even though I haven't heard before that UDP hole punching applies to broadcast packets somehow), so I went to services and disabled Windows firewall service altogether. This changed nothing.

However, after trying everything else, I re-enabled the firewall service, and tried to run the program again. This time, firewall prompt appeared asking me whether I want to allow MyProgram.vshost.exe process (I was debugging in Visual Studio) through firewall, I accepted it, and voila - everything worked! Incoming packets were being received now!

like image 179
lxa Avatar answered Oct 04 '22 21:10

lxa