I send datagrams using this socket:
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint ep = new IPEndPoint(IPAddress.Broadcast, port);
(then use the SendTo method)
To listen at the other end, I use this socket:
this.udpListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.udpListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
EndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
this.udpListenSocket.Bind(localEndPoint);
and this works as expected. It seemed a little crude to me though and I was wondering whether this could cause me to get the same datagram multiple times, once from each of the machine's IP addresses (which does not seem to be the case but this is not the point). So I tried to bind to a specific address, like the one provided by the DHCP server.
This however does not work, I get nothing. I only get something from the listening socket when binding to IPAddress.Any.
Why? Do I need to specify extra socket options? Am I misinterpreting something?
CodePudding user response:
When you bind socket to specific ip address which is not IPAddress.Any
(0.0.0.0, special one) - you will only receive packets with destination ip set to this address. The broadcast packet you send has destination address IPAddress.Broadcast
(255.255.255.255), it does not match the ip you bound your socket to. So even though this packet actually arrives to the target interface, and in theory you could receive it - it will be dropped because of destination mismatch.
For this reason the most common approach to receive UDP broadcast packages is to bind to 0.0.0.0. However, if sender does not use limited broadcast address (255.255.255.255) but instead uses broadcast address of specific subnet - then you can receive it on the same broadcast address of specific subnet.
For example, I have local IP 192.168.0.105, and broadcast address of this subnet is 192.168.0.255. If you change your sender code to broadcast to this address, and change your receiver code to bind to this address (and not to ip address of your interface, so NOT to 192.168.0.105 in my example) - then you will receive the broadcast the way you wanted.