0
votes

I have a simple UDP listener that I am trying to collect datagrams from. My datagrams can be in one of two data formats. With the first data format, I am receiving data in my program as expected. With the second, there is absolutely no indication that data is ever received from my program, even though I can verify that the UDP data is passing onto the the network interface via Wireshark. I thought that maybe these were malformed UDP packets that Windows was rejecting but Wireshark does label them as UDP. My code is below:

    static void Main(string[] args)
    {
        Thread thdUdpServer = new Thread(new ThreadStart(serverThread));
        thdUdpServer.Start();
    }

    static void serverThread()
    {

        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(new IPEndPoint(new IPAddress(0), 2000));

        while (true)
        {
            byte[] responseData = new byte[128];
            socket.Receive(responseData);
            string returnData = Encoding.ASCII.GetString(responseData);
            Console.WriteLine(DateTime.Now + " " + returnData);

        }

The missing packets are all 29 byte datagrams that look something like this (translated to ASCII).

#01RdFFFF...?...... ........F

Why would Wireshark indicate their presence but .NET not seem to see them?

2

2 Answers

2
votes

If the bytes contain non-printable ASCII characters, you may not see them on the Console.

0
votes

There's something missing in your code. It should be throwing a socket exception when calling ReceiveFrom (at least according to MSDN, haven't tried your code.)

You should bind your socket to the address:port you want to listen on (or use 0.0.0.0 as the address to listen on any local address):

socket.Bind(new IPEndPoint(new IPAddress(0), 2000);

The EndPoint in ReceiveFrom is not the listening port for the server. It's the address you want to receive packets from. You can use an Endpoint of 0.0.0.0:0 to receive from any host.

After returning from the method the Endpoint will be filled with the address of the host that sent the packet (client).

You can use Receive instead of ReceiveFrom if you don't care about the client end point. Likely your client is not sending packets from 192.168.1.100:2000, and that is why you are not receiving them; thought why you're not getting an exception when calling ReceiveFrom is beyond me.

Also: There is no need to call Convert.ToInt32 in:

new IPEndPoint(IPAddress.Parse("192.168.1.100"), Convert.ToInt32(2000));

2000 is already an int.