在释放进程退出端口绑定 [英] Releasing bound ports on process exit
问题描述
我如何确保绑定到端口的套接字正确的进程退出释放,这样的端口可以不绑定(重复使用)与EADDRINUSE失败?我写了一个小程序刚刚创建一个套接字,将其绑定到一个固定的端口,等待连接,然后立即终止。当我重新运行该程序,在bind()调用失败,EADDRINUSE,但如果我等待几分钟,它成功。
How do I make sure that a socket bound to a port is properly release 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?
推荐答案
使用SO_REUSEADDR套接字选项可以让你毫不拖延地重新启动该程序。
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))
...
这篇关于在释放进程退出端口绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!