Sending multiple messages via send() recv(), Socket programming, C

ragnaroh picture ragnaroh · Nov 13, 2010 · Viewed 40.1k times · Source

I'm trying to make a program (client) which kan send a message to a server upon request from user. Stripped down code follows:

Client:

int main(int argc, char **argv) {

  struct sockaddr_in servaddr;
  int sock = socket(AF_INET, SOCK_STREAM, 0);

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_port = htons(6789);
  servaddr.sin_addr.s_addr = inet_addr(<ip_address_of_server>);

  while(1) {

    char message[161];
    fgets(message, 161, stdin);

    /* Replacing '\n' with '\0' */
    char *tmp = strchr(message, '\n');
    if (tmp) *tmp = '\0';

    connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr));
    send(sock, message, strlen(message), 0);
    close(sock);
  }
}

Server:

int main(int argc, char **argv) {

  struct sockaddr_in servaddr;  
  int sock = socket(AF_INET, SOCK_STREAM, 0);

  memset(&servaddr, 0, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servaddr.sin_port = htons(6789);

  bind(sock, (struct sockaddr *)&servaddr, sizeof(servaddr));  
  listen(sock, 5);

  while(1) {
    int clisock = accept(sock, (struct sockaddr *) NULL, NULL);

    if (clisock >= 0) {
      int messageLength = 160;
      char message[messageLength+1];
      int in, index = 0, limit = messageLength;

      while ((in = recv(clisock, &message[index], messageLength, 0)) > 0) {
        index += in;
        limit -= in;
      }

      printf("%s\n", message);
    }

    close(clisock);
  }
}

Now, this works for the first message I send. But then it is not able to make another connection (I get the error message "Bad file descriptor" when trying to connect in the Client program.) Can anyone see what I have misunderstood? Thank you :)

Answer

Yusuf Khan picture Yusuf Khan · Nov 13, 2010

your client programme also does the same mistake, first time you open the socket but after the first connection is done you close the socket, so the next time in the loop the socket descriptor is not valid, you need to re-open the socket but that's missing, please remove the socket call from top and add the below line in the start of while loop

int sock = socket(AF_INET, SOCK_STREAM, 0);