Skip to content

Instantly share code, notes, and snippets.

@Charles-Hsu
Created January 18, 2017 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Charles-Hsu/6248443d1fd3f7903a0d4c7a34de5307 to your computer and use it in GitHub Desktop.
Save Charles-Hsu/6248443d1fd3f7903a0d4c7a34de5307 to your computer and use it in GitHub Desktop.
socket_server()
{
int sockfd, newsockfd, portno;
struct sockaddr_in serv_addr, cli_addr;
socklen_t addrlen;
int pid;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror ("ERROR opening socket");
exit (1);
}
int enable = 1;
if (setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) == -1) {
perror("Setsockopt");
exit(1);
}
/* Initialize socket structure */
bzero((char*) &serv_addr, sizeof(serv_addr));
portno = DEFAULT_SDU_SOCKET_NUMBER;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons (portno);
/* Now bind the host address using bind() */
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) {
perror ("ERROR on binding");
exit (1);
}
/* Now start listening for the clients, here process will
* go in sleep mode and will wait for the incoming connection
*/
/* Prepare to accept connections on socket FD.
N connection requests will be queued before further requests are refused.
Returns 0 on success, -1 for errors. */
printf ("Listening port %d\n", portno);
listen(sockfd, 5); /* The traditional value for listen()’s backlog parameter is 5. */
/* SOMAXCONN 128 defined in sys/socket.h */
addrlen = sizeof(cli_addr);
/* Handle multiple connections */
while (1) {
/* Accept actual connection from the client */
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &addrlen);
printf ("ACCEPT %d\n", newsockfd);
if (newsockfd < 0) {
perror ("ERR on accept");
exit (1);
}
#define MULTIPLE_CONNECTION 1
#if MULTIPLE_CONNECTION
/* Create child process */
pid = fork();
if (pid < 0) {
perror ("ERROR on fork");
exit (1);
}
else if (pid == 0) { /* This is the client process */
close (sockfd); /* close server socket */
#endif
sdu_cmds_processing (newsockfd); /* talk to client by newsockfd */
#if MULTIPLE_CONNECTION
exit (0);
}
else { /* This is the parent process */
#endif
DEBUG_log ("PARENT: fork psid %d\n", pid);
close (newsockfd); /* close client socket */
printf ("close client socket\n");
#if MULTIPLE_CONNECTION
}
#endif
}
printf ("Bye\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment