simple echo server version 2

D33wakar 0 Tallied Votes 348 Views Share

Similar to echoserver, but this one handles multiple clients by forking the process.

/* simpleserver_v2.c */
/* Simple server written in C */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>        /* misc. UNIX functions */

#include <sys/socket.h>    /* socket definitions */
#include <sys/types.h>     /* socket types */
#include <arpa/inet.h>     /* inet (3) functions */
void handle_conn(int conn_s);

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

    int list_s;    /* listening socket */
    int conn_s;    /* connecting socket */
    short int port = 1337;/* default port */

    /* set up socket address structure */
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));    /* set everything to zero */
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY); 
    servaddr.sin_port = htons(port);

    /* create the listening socket */
    if((list_s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        printf("could not create socket\n");
        exit(EXIT_FAILURE);
    }

    /* This will allow us to use the socket often */
    int yes = 1;
    setsockopt(list_s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

    /* bind the listening socket to server address and listen */
    if(bind(list_s, (struct sockaddr*) &servaddr, sizeof(servaddr)) < 0) {
        printf("binding failed, exiting.\n");
        exit(EXIT_FAILURE);
    }

    if(listen(list_s, 10) < 0) {
        printf("error calling listen()\n");
        exit(EXIT_FAILURE);
    }


    /* Enter an infinite loop to respond to client requests */
    while(1) {
        /* listen for the incoming clients */
        if((conn_s = accept(list_s, NULL, NULL)) < 0) {
            printf("error calling accept()\n");
            exit(EXIT_FAILURE);
        }

        /* fork the process to handle multiple clients */
        pid_t child_pid = fork();
        if(child_pid == -1) {
            fprintf(stderr, "fork() failed\n");
            exit(EXIT_FAILURE);
        } else if(child_pid == 0) {
            /* inside child process */
            handle_conn(conn_s);
        }
        /* Close the connection socket */
        if(close(conn_s) < 0) {
            printf("error calling close()\n");
            exit(EXIT_FAILURE);
        }



    }            
    return 0;
}



void handle_conn(int conn_s) {

    char* msg = "Welcome to the simple server v 0.1\n";  /* Welcome message */
    char buffer[1024] = {0};

    /* Send the welcome message to the client */
    send(conn_s, msg, strlen(msg), 0);

    do {
        recv(conn_s, buffer, sizeof(buffer), 0);
    } while(strncmp(buffer,"/quit\r\n", strlen(buffer)) != 0 &&
            send(conn_s, buffer, sizeof(buffer), 0)&&
            memset(buffer, 0, sizeof(buffer)));

}