Hey all.

I have some socket code, which binds to a port and then accepts
connections. Every time I try to read() from the socket, I get a EINVAL. I
am sure that I am doing something grossly stupid, and was wondering if
anyone could tell me what I had missed.

Sorry about the big code dump, I have tried to trim it down a bit.

Thanks,
Mikal

--- Code ---

  if((socketfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
    switch(errno){
      ...boring error checking...
    }

  // We bind to the port number that we want to be listening on
  bindaddr.sin_family = AF_INET;
  bindaddr.sin_port = htons(8601);
  bindaddr.sin_addr.s_addr = htonl(INADDR_ANY);

  if(bind(socketfd, (struct sockaddr *) &bindaddr, sizeof(bindaddr)) ==
-1)
    switch(errno){
      ...boring error checking...
    }

  // Listen for connections
  if(listen(socketfd, SOMAXCONN) == -1)
    switch(errno){
      ...boring error checking...
    }

  // Accept connections
  connaddrlen = sizeof(struct sockaddr);

  while(1){
    if(accept(socketfd, (struct sockaddr *) &connaddr, &connaddrlen) ==
-1)
      switch(errno){
        ...boring error checking...
      }

    // Fork to deal with the requests
    switch(fork()){
    case 0:
      // We are the child

      // Now we do something with this connection
      printf("Connection from %s, port %d\n",
             inet_ntoa(connaddr.sin_addr),
             ntohs(connaddr.sin_port));

      sleep(5);

      // We need to get the port from the connection
      read(socketfd, readBuffer, 6) == -1)
        switch(errno){
          ...I always end up in here with an EINVAL...
      }

      printf("Server reported it was on port %s\n", readBuffer);

      // Store this information in the connections database for
      // later consumption
      key.dptr = dst_sprintf(&key.dsize, "%s",
        inet_ntoa(connaddr.sin_addr));
      data.dptr = dst_sprintf(&data.dsize, "%d", atoi(readBuffer));
      if (tdb_store(conndb, key, data, TDB_REPLACE) != 0)
        dst_error(1, "Failed to log the connection properly");

      // Done!
      close(socketfd);
      exit(0);
      break;

      case -1:
      // An error
      dst_error(1, "Fork error on new connection");
      break;

      default:
      // We are the parent -- go listen for the next connection
      break;
      }

-- 
Michael Still ([EMAIL PROTECTED])
  http://www.stillhq.com -- a whole bunch of Open Source stuff including PDF 
software...

"Grrrrrrr! I'm a volleyballing machine!"


-- 
SLUG - Sydney Linux User Group Mailing List - http://slug.org.au/
More Info: http://lists.slug.org.au/listinfo/slug

Reply via email to