Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can only connect to Server once with Client in c

I'm writing in C and creating a Server that receives connections from multiple different Clients one at a time. However, after the first connection closes, the server can't be connected to again.

server.c:

#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <sys/types.h>

#include <netinet/in.h>
#include <unistd.h>

int main() {
 while(1) {
  char server_message[256] = "You have reached the server!";

  //Create a socket
  int server_socket;
  server_socket = socket(AF_INET, SOCK_STREAM, 0);

  //Define the server address
  struct sockaddr_in server_address;
  server_address.sin_family = AF_INET;
  server_address.sin_port = htons(9002);
  server_address.sin_addr.s_addr = INADDR_ANY;

  //Bind the socket to the IP and port
  bind(server_socket, (struct sockaddr *) &server_address, 
  sizeof(server_address));

  //Listen for connections
  listen(server_socket, 5);

  //Accept the connection
  int client_socket = accept(server_socket, NULL, NULL);

  //Send message
  send(client_socket, server_message, sizeof(server_message), 0);

  //Close the socket
  close(server_socket);
  }
 return 0;
}
like image 341
M. Dennis Avatar asked Dec 05 '25 04:12

M. Dennis


1 Answers

You're looping creating a server socket, accepting one connection, processing it, and then closing your server socket. The last action will throw away all pending connections. Your loop should start immediately after the listen() call and terminate after closing the client socket, and before closing the server socket.

You are also ignoring all errors on socket(), bind(), listen(), accept(), send(), and close(). Don't do that.

like image 85
user207421 Avatar answered Dec 07 '25 19:12

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!