WCF: System.Net.SocketException – Only one usage of each socket address (protocol/network address/port) is normally permitted

You are overloading the TCP/IP stack. Windows (and I think all socket stacks actually) have a limitation on the number of sockets that can be opened in rapid sequence due to how sockets get closed under normal operation. Whenever a socket is closed, it enters the TIME_WAIT state for a certain time (240 seconds IIRC). Each time you poll, a socket is consumed out of the default dynamic range (I think its about 5000 dynamic ports just above 1024), and each time that poll ends, that particular socket goes into TIME_WAIT. If you poll frequently enough, you will eventually consume all of the available ports, which will result in TCP error 10048.

Generally, WCF tries to avoid this problem by pooling connections and things like that. This is usually the case with internal services that are not going over the internet. I am not sure if any of the wsHttp bindings support connection pooling, but the netTcp binding should. I would assume named pipes does not run into this problem. I couldn’t say for the MSMQ binding.

There are two solutions you can use to get around this problem. You can either increase the dynamic port range, or reduce the period of TIME_WAIT. The former is probably the safer route, but if you are consuming an extremely high volume of sockets (which doesn’t sound like the case for your scenario), reducing TIME_WAIT is a better option (or both together.)

Changing the Dynamic Port Range

  1. Open regedit.
  2. Open key HKLM\System\CurrentControlSet\Services\Tcpip\Parameters
  3. Edit (or create as DWORD) the MaxUserPort value.
  4. Set it to a higher number. (i.e. 65534)

Changing the TIME_WAIT delay

  1. Open regedit.
  2. Open key HKLM\System\CurrentControlSet\Services\Tcpip\Parameters
  3. Edit (or create as DWORD) the TcpTimedWaitDelay.
  4. Set it to a lower number. Value is in seconds. (i.e. 60 for 1 minute delay)

One of the above solutions should fix your problem. If it persists after changing the port range, I would see try increasing the period of your polling so it happens less frequently…that will give you more leeway to work around the time wait delay. I would change the time wait delay as a last resort.

Leave a Comment