title: BIND ERROR : Address already in use
body: <p>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? </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;stdlib.h&gt;
  
  
  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(&amp;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 *) &amp;servaddr,sizeof servaddr)&lt;0){
  perror("BIND");
  exit(0);
  }
  
  
  
  //listen
  if(listen(listenfd,20)&lt;0){
  perror("LISTEN");
  exit(0);
  
  }
  
  
  //accept
  int counter = 1;
  clilen = sizeof cliaddr;
  while(counter&lt;3){
  
  clientfd = accept(listenfd,(struct sockaddr *) &amp;cliaddr,&amp;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); 
  } 
  </code></pre>
  
  <p>Thanks</p>