Sending and receiving UDP packets in .NET

10,939

Solution 1

Well, if the same code works on one and not the other, it's your environment. Check your firewall settings, make sure it's not preventing the broadcast on the sender or preventing receipt on the receiver. Wireshark (or even Windows' netmon) should be helpful here.

Solution 2

Try using the async methods so that you can keep listening for messages without blocking to send messages.

Share:
10,939
Reixons
Author by

Reixons

Updated on June 27, 2022

Comments

  • Reixons
    Reixons almost 2 years

    I am trying to test UDP communications on a LAN. I have a small piece of code to and I have tried to run it in 2 computers (one should wait to receive and the other one should send). The strange thing is that computer A sends and B receives properly but if I try A to receive and B to send it does not work. Do you know why could it be?

    public void SendBroadcast(int port, string message)
        {
            UdpClient client = new UdpClient();
            byte[] packet = Encoding.ASCII.GetBytes(message);
    
            try
            {
                client.Send(packet, packet.Length, IPAddress.Broadcast.ToString(), port);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    
    public void Receive(int port)
        {
            UdpClient client = null;
    
            try
            {
                client = new UdpClient(port);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
    
            IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
    
    
            while (true) 
            {
                try
                {
                    byte[] packet = client.Receive(ref server);
                    Console.WriteLine("{0}, {1}", server, Encoding.ASCII.GetString(packet));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    

    And the calls:

      SendBroadcast(444, "hello"); Receive(444);
    

    If I run 2 instances of the program on the same computer it works properly but creates 3 packages per call.

    Thanks in advance.

  • Reixons
    Reixons almost 13 years
    Yes that is the problem... Thanks!
  • WEFX
    WEFX over 12 years
    can you elaborate on the async methods. Any links available? Thanks
  • Jay
    Jay over 12 years
    Here is a link to the MSDN documentation. Look for the methods that start with 'Begin' and 'End'. There are plenty of examples to be found here.