1

I'm making a program which needs to be listening for UDP Data at all times.

My current idea is have this method running constantly in one thread listening for packets and then adding them to a list ready to be dealt with in other threads. The main problem is I would also like to add the received IP to a list so that the other thread can deal with it but I don't know if the program stops using the Receive method for a moment if it will lose packets received while processing the data or if it can still grab them from a queue.

public void listen()
{
    try
    {
        packetQueue.Add(receivingUdpClient.Receive(ref RemoteIpEndPoint)); 
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}
George Brighton
  • 5,131
  • 9
  • 27
  • 36
Joel
  • 587
  • 1
  • 5
  • 17

2 Answers2

1

I know of no way to get the IP from the Udp packet. You need to get it form the EndPoint:

 byte[] receivedBytes = oClientListener.Receive(ref endPoint);
 IPAddress = endPoint.Address;
 PackQueue.Add( new PacketOfSomeType( receivedBytes, IPAdress ) );

Also, your program will need to run VERY SLOWLY to start losing any packets - windows will buffer those for you, so long as you have your client listener set up!

DanTheMan
  • 3,277
  • 2
  • 21
  • 40
  • are you sure that's just windows buffering it? I thought network cards buffer – mtijn Jan 19 '12 at 15:57
  • Ah, yeah, I reread your question and edited my answer. No, your traffic will be buffered as long as the UdpClient is alive. – DanTheMan Jan 19 '12 at 15:57
  • I wouldn't downplay the performance aspects. UDP packets can come in fast-and-furious (think SQL Slammer) due to the lack of a connection. Just something to keep in kind. – Andrew Barber Jan 19 '12 at 15:57
  • @mtijn: Yes, the OS has a network buffer, I'm sure of it. Now, how much is held in the OS and how much is held on the card, I'm not sure. – DanTheMan Jan 19 '12 at 16:00
  • @AndrewBarber: I guess the idea is just don't take longer to process than the expected average time between packets. – DanTheMan Jan 19 '12 at 16:02
1

network traffic should be buffered on your network card so the data should be consistent even if you are listening inconsistently. as for the IP you can get it from the endpoint so you'll need to pass that as well:

public void listen()
  {
      try
      {
          packetQueue.Add(receivingUdpClient.Receive(ref RemoteIpEndPoint), RemoteIpEndPoint);
       }
      catch (Exception e)
      {
          Console.WriteLine(e.ToString());
      }
  }

If you want to miss as little time as possible in between receives I suggest you use BeginReceive and start a new BeginReceive in the callback before processing the received data in the callback. this will add some synchronization complexity though.

mtijn
  • 3,610
  • 2
  • 33
  • 55