20

How do I make sure that a socket bound to a port is properly released on process exit such that the port can be reused without bind() failing with EADDRINUSE? I've written a tiny program which just creates a socket, binds it to a fixed port, waits for a connection and then immediately terminates. When I rerun the program, the bind() call fails with EADDRINUSE, but if I wait a few minutes, it succeeds.

Is there a way I can explicitly "unbind" the socket, thereby freeing the port number?

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
JesperE
  • 61,479
  • 20
  • 135
  • 194

3 Answers3

26

Using SO_REUSEADDR socket option will allow you to re-start the program without delay.

int iSetOption = 1;
...
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&iSetOption,
        sizeof(iSetOption))
...         
Ivo Bosticky
  • 6,218
  • 6
  • 33
  • 34
  • 3
    But note that technically, using SO_REUSEADDR violates the TCP/IP protocol, making it possible (though unlikely) for the next program that binds that port to pick up packets intended for the original program. – j_random_hacker Feb 14 '09 at 14:09
  • Excellent, exactly what I was looking for. – JesperE Feb 15 '09 at 09:20
5

TCP/IP stack keeps port busy for sometime even after close() - socket will stay in TIME_WAIT and TIME_WAIT2 state.

If I'm not mistaken, usually it takes 2 minutes so if you need to use the same port immediately set SO_REUSEADDR option on your socket before binding, just like Ivo Bosticky suggested.

qrdl
  • 32,678
  • 14
  • 55
  • 84
4

Not exactly an answer to your question, but for completeness:

On Windows you can set the TcpTimedWaitDelay registry value to set the timeout for releasing closed TCP connections to as low as 30 seconds.

Amnon
  • 7,462
  • 2
  • 25
  • 34