Releasing bound ports on process exit

前端 未结 3 525
野趣味
野趣味 2020-12-05 08:04

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

相关标签:
3条回答
  • 2020-12-05 08:39

    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.

    0 讨论(0)
  • 2020-12-05 08:54

    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))
    ...         
    
    0 讨论(0)
  • 2020-12-05 08:55

    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.

    0 讨论(0)
提交回复
热议问题