Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending UDP broadcast, receiving multiple messages

I've got 2 programs, 1 for sending an UDP broadcast message and 1 that is listening for this broadcast. My problem is that sometimes when I send a broadcast, the receiver receives 2 messages. Why?

Receiver code:

public class Receiver {   private readonly UdpClient udp = new UdpClient(15000);   private void StartListening()   {     this.udp.BeginReceive(Receive, new object());   }   private void Receive(IAsyncResult ar)   {     IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000);     byte[] bytes = udp.EndReceive(ar, ref ip);     string message = Encoding.ASCII.GetString(bytes);     StartListening();   } } 

Sender code:

public class Sender {   public void Send() {     UdpClient client = new UdpClient();     IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);     byte[] bytes = Encoding.ASCII.GetBytes("Foo");     client.Send(bytes, bytes.Length, ip);     client.Close();   } } 
like image 851
Paw Baltzersen Avatar asked May 31 '12 11:05

Paw Baltzersen


People also ask

Does UDP support broadcasting?

UDP stands for User Datagram Protocol and is one of the core protocols of the Internet Protocol (IP) suite. As for the Broadcast term, it describes the process of broadcasting packets to an entire subnet.

What is broadcast address in UDP?

A UDP broadcast packet is 'sent' to an IP address with the subnet of the broadcasting device and all 1's in the host portion. For example, if a device has an address 128.253. 109.10 and a subnet mask 255.255. 255.0, it can use the broadcast address 128.253. 109.255.


2 Answers

Strictly speaking, packet duplication in IP network is allowed behavior of the network and you have to be able to deal with it in your software even if you will somehow get rid of it this time. If you are just wondering about why this happens in your particular case... at a first glance I see nothing wrong with your code. Do you have several IP addresses on Ethernet port of your computer or some such? I think wireshark might help get more details about what's going on.

like image 116
Eugene Ryabtsev Avatar answered Oct 15 '22 10:10

Eugene Ryabtsev


UDP packets aren't reliable, it's totally possible that you'll get the same packet twice or even none at all, when using udp you need to include some kind of unique ID in your data so you can discard errors or request a resend.

like image 31
Andy Avatar answered Oct 15 '22 11:10

Andy