Windows – Cannot start listening on a certain TCP port, but there’s nothing currently listening on it

porttcpwindows

I have Windows Service that uses a WCF service host to listen for connections on TCP port 61000. When I try to start the service, I get the error:

Service cannot be started. System.ServiceModel.AddressAlreadyInUseException: HTTP could not register URL http://+:61000/ because TCP port 61000 is being used by another application. ---> System.Net.HttpListenerException: The process cannot access the file because it is being used by another process
   at System.Net.HttpListener.AddAll()
   at System.Net.HttpListener.Start()
   at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
   --- End of inner exception stack trace ---
   at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()
   at System.ServiceModel.Channels.TransportManager.Open(TransportChannelListener channelListener)
   at System.ServiceModel.Channels.TransportManagerContainer.Open(SelectTransportManagersCallback selectTransportManagerCallback)
   at System.ServiceModel.Channels.HttpChannelListener.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout)
   at...

A quick netstat -a shows there is nothing listening on port 61000. I've also found several posts online that mention reserving namespaces using netstat, but the account that the service runs under has administrator privileges so that shouldn't be necessary.

Any other ideas as to why I'm getting this message?

This service is running on 64-bit Windows Server 2008 R2 Standard.

Best Answer

If there was an open connection on the port when the program was closed, and TCP didn't complete the 4-way close handshake, then the socket will remain "half-closed" until the timeout has expired (even though the program has terminated), and will prevent you from opening that port again. Various implementations have different timeouts usually ranging from 1/2 second to 2 minutes.