Home > Net >  UDP port is not free after closesocket call (Windows)
UDP port is not free after closesocket call (Windows)

Time:11-11

I have two listening sockets (created by calls to socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)), at this moment they are maintained from one thread.

After creating, they have to be closed (closesocket(...)) and reopened again on the same ports. But bind(...) call returns error 10048 WSAEADDRINUSE on one of these sockets (the second one is opened successfully), and I see by using netstat that the UDP port stays open (closesocket(...) returned no error, SO_REUSEADDR always set to TRUE on all sockets). And this "closed" UDP port stays open as long as the 2nd socket is open (they have no relation, but the "closed" port is closing a second after the 2nd socket is closed).

Let's summarize:

  1. Open sockets and bind them to ports 8888 and 9999.
  2. Close 8888 socket, create new socket, bind it to port 8888 -> success.
  3. Close 9999 socket, create new socket, and try to bind it to port 9999 -> error WSAEADDRINUSE.
  4. Close 8888 socket -> success.
  5. After about a second after #4, port 9999 is freed (by observing in external tool).

I have discovered something similar to my problem: https://stackoverflow.com/a/26129726/10101917, but in my case moving all socket operations to one thread does not solve the problem.

What is happening here?

CodePudding user response:

I have found what caused this problem. The thing I have programmed is the DLL. I have discovered, that another DLL from this app is using QProcess class of Qt library version 5.7.1. I have checked sources of Qt and discovered that this class actually starts process with bInheritHandles set to TRUE. When I manually have reset this value to FALSE all issues were gone.

It is obvious that the issue was caused by the following: one of UDP socket handles was inherited by child process and that process didn't let socket handle to be closed, until that process stop.

Thanks to this comment for pointing to the solution.

  • Related