简体   繁体   English

绑定端口“地址已在使用中”时出错Unix中的TCP套接字编程

[英]error in binding port “Address already in use” TCP socket programming in unix

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 我的代码的大部分与BIND ERROR相似:地址已在使用中

but then i changed my code so that i include "setsockopt" function like so: 但是后来我更改了代码,以便包含“ 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!");
}

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

Check to see if the port is in use. 检查端口是否正在使用中。 Either telnet to that port or use netstat -a . telnet该端口或使用netstat -a It should be in use (as the error indicates) and kill the appropriate process. 它应该在使用中(如错误所示),并终止相应的进程。 Perhaps using ps to find the process. 也许使用ps查找过程。

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. SO_REUSEADDR用于绑定到某个地址的套接字已经关闭时,可以直接再次使用相同的地址(ip地址/端口对)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM