在进程退出时释放绑定端口 [英] Releasing bound ports on process exit

查看:39
本文介绍了在进程退出时释放绑定端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保在进程退出时正确释放绑定到端口的套接字,以便可以重用端口,而 bind() 不会因 EADDRINUSE 而失败?我写了一个小程序,它只是创建一个套接字,将它绑定到一个固定端口,等待连接然后立即终止.当我重新运行程序时,bind() 调用失败并显示 EADDRINUSE,但如果我等待几分钟,它就会成功.

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?

推荐答案

使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆