BIND ERROR: address already in use

I study socket programming in c, I wrote this simple program to accept connections on port 5072. I connect to it using telnet. This works fine for the first time, but when I try to start it again, it doesn't show BIND: the address is already in use, but then starts working again 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); 
} 

thank

+3
source share
2 answers

You should setsockopt(SO_REUSEADDR)

See this faq for an explanation of the reasons.

+8
source

. TCP/IP , - , .

-2

Source: https://habr.com/ru/post/1730226/


All Articles