重新创建套接字时绑定错误 [英] Bind error while recreating socket
本文介绍了重新创建套接字时绑定错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
A 有以下侦听器套接字:
A have the following listener socket:
int sd = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(http_port);
addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sd,(sockaddr*)&addr,sizeof(addr))!=0)
{
...
}
if (listen(sd, 16)!=0)
{
...
}
int sent = 0;
for(;;) {
int client = accept(sd, (sockaddr*)&addr, (socklen_t*)&size);
if (client > 0)
{
...
close(client);
}
}
如果使用
close(sd);
然后尝试使用相同的代码重新创建套接字,发生绑定错误,并且仅在 30-60 秒后成功创建新套接字.
and then trying to recreate socket with the same code, a bind error happens, and only after 30-60 second a new socket is created successfully.
有没有办法以某种很酷的方式创建或关闭来避免绑定错误?
It there a way to create or close in some cool way to avoid bind error?
推荐答案
在内核的某个地方,仍然有一些关于您以前的套接字的信息.告诉内核你无论如何都愿意重用这个端口:
Somewhere in the kernel, there's still some information about your previous socket hanging around. Tell the kernel that you are willing to re-use the port anyway:
int yes=1;
//char yes='1'; // use this under Solaris
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
perror("setsockopt");
exit(1);
}
参见 beej 网络编程指南中的 bind() 部分 更详细的解释.
See the bind() section in beej's Guide to Network Programming for a more detailed explanation.
这篇关于重新创建套接字时绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文