views:

105

answers:

4

Can someone explain to me why this code fails once in a while with a null exception for udpLink while sending?

            udpLink = new UdpClient(ipAddress, 514);
            using (udpLink)
            {
                  udpLink.Send(rawMsg, rawMsg.Length);
            }

This is the new code on how I fixed it.

            udpLink = new UdpClient(ipAddress, 514);
            using (udpLink)
            {
                  if (udpLink != null) udpLink.Send(rawMsg, rawMsg.Length);
            }

Any ideas?

+1  A: 

Using udp what?

What are you attempting there?

leppie
I'm sending a udp packet to a syslog server.
Rick
+1  A: 

I'm not sure if it really is the problem, but I guess it's the way how you use the using statement. I would do it like this:

using (UdpClient udpLink = new UdpClient(ipAddress, 514))
{
    udpLink.Send(rawMsg, rawMsg.Length);
}
Enyra
Functionally, that's the same, all you did was remove a line of code.
Jonathan
I wrote, I'm not sure if it helps...
Enyra
I'm not sure why this worked, but it did. I've been running the code for sometime now with not even one exception after I made your suggested code change. Thank you.
Rick
A: 

I don't see any reason why you should be getting a null pointer exception on udpLink. You are sure its udpLink that is null and not rawMsg? Also, you're sure you are throwing a NullPointerException and not a SocketException or other exception?

heavyd
+2  A: 

Depending on whether or not this code segment is in a loop that executes thousands of times you might be maxing out on connections (speaking from experience). you can do a netstat -an and if it scrolls for more than a second chances are that could be your problem.

Hardwareguy