Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Experiment 8: A Web Server Using Sockets

Lesson 8 of 11 in the free Network Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Program Statement

A minimal HTTP/1.0 server using the classic fork-per-client model:

/* webserver.c — minimal HTTP/1.0 server, fork-per-client */
int main(void) {
    int lfd = socket(AF_INET, SOCK_STREAM, 0), on = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    struct sockaddr_in a = {0};
    a.sin_family = AF_INET; a.sin_port = htons(8080);
    a.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(lfd, (struct sockaddr *)&a, sizeof(a));
    listen(lfd, 16);
    signal(SIGCHLD, SIG_IGN);                 /* auto-reap children */
    for (;;) {
        int cfd = accept(lfd, NULL, NULL);
        if (fork() == 0) {
            close(lfd);
            char req[4096];
            read(cfd, req, sizeof(req));      /* read request       */
            printf("request line: %.40s\n", req);
            const char *body = "<h1>Hello from my socket web server!</h1>";
            char resp[512];
            int len = snprintf(resp, sizeof(resp),
                "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n"
                "Content-Length: %zu\r\n\r\n%s", strlen(body), body);
            write(cfd, resp, len);
            close(cfd); exit(0);
        }
        close(cfd);                           /* parent MUST close  */
    }
}

Testing

Open http://localhost:8080 in a browser.

Extension

Parse the request path and serve actual files from disk.

Theory Link

Unit 1 "Concurrent Servers" — note SO_REUSEADDR (restart the server while old connections sit in TIME_WAIT) and the parent's close(cfd) (without it the connection never fully closes because the descriptor's reference count stays above zero). Both are exam points.