-3

I listen socket port 4000 in my process. I start another process using CreateProcess witch using another port number. after exit my process, when i try to start it again i received this error even when the child process is killed:

Only one usage of each socket address (protocol/network address/port) is normally permitted.

But when i start this process normally from explorer the is no conflict happens. What should i do to release the port for my usage?

Edit: I use this code to create the new process.

CreateProcessW(NULL, pwszCommandLine, NULL, NULL, TRUE, 
              NORMAL_PRIORITY_CLASS | CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, 
              NULL, NULL, &si, &pi)
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);

I don't wait to process finish, because this process should not exit.

  • 2
    Probably the answer is to be found in the code. [mcve]. – David Heffernan Nov 12 '19 at 07:09
  • 1
    The original socket is likely in the `TIME_WAIT` state. As such its bound IP/Port can't be reused for a new socket until the old socket times out and is released by the OS. Unless you use the `SO_REUSEADDR` socket option on the sockets – Remy Lebeau Nov 12 '19 at 07:57
  • are you start new process with inherited handles ? socket by default was inherited handle – RbMm Nov 12 '19 at 08:08
  • @RbMm how can i prevent to inherit? – wildfire enterprise Nov 12 '19 at 12:05
  • yes, you use `bInheritHandles = true` in call `CreateProcess` - at first - are this actually need ? if you need concrete handles to be inherit - describe it with `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` - as result only this handles will be inherited. and in call `WSASocket` - exist option `WSA_FLAG_NO_HANDLE_INHERIT` (This flag is supported from Windows 7 with SP1) – RbMm Nov 12 '19 at 12:17
  • @RbMm Thank you. I was confused changing flags to handle this problem. The problem solved. Thanks – wildfire enterprise Nov 12 '19 at 13:36

1 Answers1

0

The close call only marks the TCP socket closed. It is not usable by process anymore. But kernel may still hold some resources for a period (TIME_WAIT, 2MLS etc stuff).

Setting of SO_REUSEADDR should remove binding problems.

So be sure that value of true is really non-zero when calling setsockopt (overflow bug may overwrite it):

true = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))

All above is from here. Is this helpful ?

Astonghdn
  • 31
  • 3
  • Actually the socket being handled in another dll witch i cant change it now. is there any other solution to create process without inherit from parent? – wildfire enterprise Nov 12 '19 at 09:52