Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 15 Sep 2001 19:49:17 -0500
From:      Stephen Montgomery-Smith <stephen@math.missouri.edu>
To:        freebsd-hackers@FreeBSD.ORG
Subject:   Could not bind
Message-ID:  <3BA3F70D.27C2136@math.missouri.edu>

next in thread | raw e-mail | index | archive | help
I have written a server program that listens on port 3000.  The program
works very well except for one feature.  I am asking if that is normal,
or whether I forgot something.

If I run the program it does fine.  If I then kill the program (after it
has accepted connections), and then run the program again, the bind
function fails to work, and I get a message like "Could not bind" (see
program below).  If I wait a while, like a minute or two, then the
program will work again. Is this normal behavior, or did I miss
something?

I got the programming style from Richard Steven's book on network
programming.  The structure of the program is something like this:


typedef struct {
  int connfd;
  struct in_addr addr;
  u_short port;
}
arg_pass_type;

void *process_client(void *arg) {
  int connfd = ((arg_pass_type*)arg)->connfd;
  struct in_addr addr = ((arg_pass_type*)arg)->addr;
  u_short port = ((arg_pass_type*)arg)->port;

  free(arg);
  pthread_detach(pthread_self());
  do_lots_of_stuff();

}

int main () {
  int listenfd;
  struct sockaddr_in servaddr;
  socklen_t slen;
  pthread_t tid;
  arg_pass_type *arg;

  listenfd=socket(AF_INET,SOCK_STREAM,0);
  bzero(&servaddr,sizeof(servaddr));
  servaddr.sin_family=AF_INET;
  servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
  servaddr.sin_port=htons(3000);
  if (bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) < 0)
  {
    fprintf(stderr,"Could not bind\n");
    exit(1);
  }
  listen(listenfd,6);

  while (1)
  {
    slen=sizeof(servaddr);
    arg = malloc(sizeof(arg_pass_type));
    arg->connfd = accept(listenfd,(struct sockaddr*)&servaddr,&slen);
    arg->addr = servaddr.sin_addr;
    arg->port = servaddr.sin_port;
    pthread_create(&tid,NULL,process_client,(void*) arg);
  }
  exit(0);
}

-- 
Stephen Montgomery-Smith
stephen@math.missouri.edu
http://www.math.missouri.edu/~stephen

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?3BA3F70D.27C2136>