Question

I have an application running on an iPhone that is broadcasting UDP packets. I want to write a console application that reads the UDP packets on my PC. I tried this example and was unable to read any packets:

http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.aspx

I used wireshark and verified that the UDP packets are being sent to 255.255.255.255 on a given port. How do I read the packets in a C# application?

Thanks!

Was it helpful?

Solution

This is the C# code for a simple listener, it should be fine but I wrote this on my Mac so I can't test it.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UDPListener
{
    public static int Main()
    {
        var done = false;
        var listener = new UdpClient(31337);
        var ipe = new IPEndPoint("255.255.255.255", 31337);
        var data = String.Empty;

        byte[] rec_array;
        try
        {
            while (!done)
            {
                rec_array = listener.Receive(ref ipe);
                Console.WriteLine("Received a broadcast from {0}", ipe.ToString() );
                data = Encoding.ASCII.GetString(rec_array, 0, rec_array.Length);
                Console.WriteLine("Received: {0}\r\rn", data);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        listener.Close();
        return 0;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top