Question

On some computers I have the strange effect that UdpClient will not send data when UdpClient.Close() is called too soon after a UdpClient.Send(). I'm using .NET 4.0 and WireShark to verify the packet-loss.

The essential part of the coding is:

UdpClient sender = new UdpClient();
sender.Connect( new IPEndPoint( this.ipAddress, this.Port ) );
int bytesSent = sender.Send( data, data.Length );
sender.Close();

Weired is:

  • On most Computers data will be sent without problems
  • There is no exception or other error even if no packet was sent
  • bytesSent will always equal data.Length
  • On computers not sending packets a Thread.Sleep( 250 ) right before calling sender.Close() will fix the problem!

So, what could cancel the sending of packets, even after UdpClient.Send() reported the correct amount of bytes? Why is this manifesting only on certain machines? Could this be a different behaviour of some network drivers, anti-virus software or the like?

I also tried to set LingerOptions explicitly which should be unneccessary as the default is to send all pending data before closing the underlying socket. However, when doing a sender.Client.LingerState = new LingerOption( true, 10 ) (as descibed in http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.lingerstate.aspx) I get

 SocketException (0x80004005): An unknown, invalid, or unsupported option 
 or level was specified in a getsockopt or setsockopt call.

Any ideas what's going on?

Regards, Seven

Was it helpful?

Solution

OK, this has nothing to do with .NET and my software either. It seems that the virus scanner also scans the complete network trafic. And so .NET library functions for sending UDP packages actially did send the package, but the scanner discards it if UdpClient.Close() was called too soon after the Send() method.

So, there are two possible work-arounds now (that worked for me)

  1. Introduce a little sleep before calling UdpClient.Close() (about 4ms are sufficient)
  2. Remove the virus scanner and try another one (Microsoft Security Essentials does not show this effect)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top