views:

65

answers:

2

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

+4  A: 

You must setsockopt(SO_REUSEADDR)

See this faq for explanation why.

Kimvais
A: 

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.

ceo
Is this answer really helpful? He is asking what he is doing wrong - besides, abhishek already mentioned that waiting for a minute solves the problem...
Kimvais