Fredou
Fredou

Reputation: 20100

udpclient.close doesn't always close the socket?

I'm using the code below, it seem sometime the socket is not released

How did I found that? by using process explorer(from sysinternal), proprieties on the application then going into TCP/IP tab.

I can see the port being used by typing "netstat -a" into a console

My problem is, after a while (like 5 weeks) there is like 40 port used by the application while it should be zero.

Anyone know why it does that?

    public void Connect()
    {
        try {
            // Resolve server address
            IPHostEntry hostadd = Dns.GetHostEntry(TimeServer);
            IPEndPoint EPhost = new IPEndPoint(hostadd.AddressList[0], 123);

            //Connect the time server
            UdpClient TimeSocket = new UdpClient();
            TimeSocket.Connect(EPhost);

            TimeSocket.Send(SNTPData, SNTPData.Length);
            SNTPData = TimeSocket.Receive(ref EPhost);                
            TimeSocket.Close();
            if (!IsResponseValid())
            {
                throw new Exception("Invalid response from " + TimeServer);
            }

        } catch(SocketException e)
          {
            throw new Exception(e.Message);
          }

    }

Upvotes: 1

Views: 2427

Answers (1)

sipsorcery
sipsorcery

Reputation: 30699

You're blocking forever on:

SNTPData = TimeSocket.Receive(ref EPhost);  

If the socket never receives a packet it will sit there waiting until the process dies.

You'll need to close the socket by calling TimeSocket.Close() on a different thread or by setting a timeout on the receive using SetSocketOption.

Upvotes: 1

Related Questions