绑定端口“地址已在使用中”时出错unix下的TCP套接字编程
我浏览了很多帖子和论坛,并且我是套接字编程的新手。我的代码的主要部分类似于 绑定错误:地址已在使用中
但后来我更改了我的代码,以便我包含“setsockopt”函数,如下所示:
const char* port="5555";
int opt=1;
portno=atoi(port);
//parameters for server address
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(portno);
serv_addr.sin_addr.s_addr=INADDR_ANY;
//bind the socket to the address
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char *)&opt,sizeof(int));
if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{close(sockfd);
error("error in binding port!");
}
但我仍然收到错误。我必须关闭终端并重新启动它才能再次使用该端口。我想使用硬编码端口(就像我在上面的代码中提到的那样)
Thanks a lot in advance
I've gone through many posts and forums and I'm new to socket programming. Major parts of my code are similar to
BIND ERROR : Address already in use
but then i changed my code so that i include "setsockopt" function like so:
const char* port="5555";
int opt=1;
portno=atoi(port);
//parameters for server address
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(portno);
serv_addr.sin_addr.s_addr=INADDR_ANY;
//bind the socket to the address
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char *)&opt,sizeof(int));
if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))<0)
{close(sockfd);
error("error in binding port!");
}
But still i get the error. I have to close the terminal and restart it in order to use the port again. I want to use a hardcoded port (like i mentioned in the code above)
Thanks a lot in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查端口是否正在使用。
telnet
到该端口或使用netstat -a
。它应该正在使用(如错误所示)并终止适当的进程。也许使用ps
来查找进程。Check to see if the port is in use. Either
telnet
to that port or usenetstat -a
. It should be in use (as the error indicates) and kill the appropriate process. Perhaps usingps
to find the process.一个端口号一次只能由一个应用程序使用。这意味着您不能两次启动同一个程序并期望它们都绑定到同一个端口。
SO_REUSEADDR
是为了当绑定到某个地址的套接字已经关闭时,可以直接再次使用相同的地址(ip-地址/端口对)。A port number can only be used by one application at a time. That means you can not start the same program twice expecting both to bind to the same port.
The
SO_REUSEADDR
is for when the socket bound to an address has already been closed, the same address (ip-address/port pair) can be used again directly.