C语言 重新创建套接字时绑定错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5592747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind error while recreating socket
提问by spe
A have the following listener socket:
A 具有以下侦听器套接字:
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);
}
}
If a use
如果一个使用
close(sd);
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.
然后尝试使用相同的代码重新创建套接字,发生绑定错误,并且仅在 30-60 秒后成功创建新套接字。
It there a way to create or close in some cool way to avoid bind error?
有没有办法以某种很酷的方式创建或关闭以避免绑定错误?
回答by Philip
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);
}
See the bind() section in beej's Guide to Network Programmingfor a more detailed explanation.
有关更详细的说明,请参阅beej 的网络编程指南中的 bind() 部分。
回答by harper
This is the expected behavior for TCP sockets. When you close a socket it goes to the TIME_WAIT state. It will accept and drop packets for this port. You need to set the SO_REUSEADDRoption to bind immediately again.
这是 TCP 套接字的预期行为。当您关闭套接字时,它会进入 TIME_WAIT 状态。它将接受和丢弃此端口的数据包。您需要再次设置SO_REUSEADDR立即绑定选项。
回答by darklion
You should not be closing the bound socket and then trying to recreate it.
您不应该关闭绑定的套接字然后尝试重新创建它。
acceptreturns a newly created socket for just that connection, it is the one that needs to be closed. ie: you should be doing -
accept为该连接返回一个新创建的套接字,它是需要关闭的套接字。即:你应该做 -
close(client);
回答by byte
Try calling setsockoptwith SO_REUSEADDR. Refer: http://msdn.microsoft.com/en-us/library/ms740476(v=vs.85).aspx
尝试调用setsockopt带SO_REUSEADDR。参考:http: //msdn.microsoft.com/en-us/library/ms740476(v=vs.85).aspx

