BIND ERROR : Address already in use

 ̄綄美尐妖づ 提交于 2020-01-04 01:59:07

问题


I am learning socket programming in c, I wrote this simple program to accept connections on port 5072. i connect to it using telnet. This works fine the first time but when i try to run it again immediately it fails showing BIND : Address already in use, but then again starts to work after a minute or so. What am i doing wromg?

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <stdlib.h>


int main(){

//variables

int listenfd, clientfd;
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;

//getsocket
if((listenfd = socket(AF_INET,SOCK_STREAM,0)) == -1){
perror("SOCKET");
exit(0);
}


//prep the servaddr
bzero(&servaddr,sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr ("127.0.0.1");
servaddr.sin_port = htons(5072);


//bind
if(bind(listenfd, (struct sockaddr *) &servaddr,sizeof servaddr)<0){
perror("BIND");
exit(0);
}



//listen
if(listen(listenfd,20)<0){
perror("LISTEN");
exit(0);

}


//accept
int counter = 1;
clilen = sizeof cliaddr;
while(counter<3){

clientfd = accept(listenfd,(struct sockaddr *) &cliaddr,&clilen);
if(clientfd == -1){
perror("ACCEPT");
exit(0);
}
if(fork()==0){
 close(listenfd);
 printf("CONNECTION NO. %d\n",counter);
close(clientfd);
exit(0);
}
counter++;
close(clientfd);
}
close(listenfd); 
} 

Thanks


回答1:


You must setsockopt(SO_REUSEADDR)

See this faq for explanation why.




回答2:


Or simply wait a couple minutes. The TCP/IP stack holds onto the socket for twice the maximum segment lifetime after close,to prevent any stray packets from the first connection from showing up after a second one's established, which will make it all confused.



来源:https://stackoverflow.com/questions/2147592/bind-error-address-already-in-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!