A web server for Unix

Posted on 2004-08-07
Last Modified: 2010-04-17
Here is the code for a web server:

#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <curses.h>
#include <sys/time.h>
#include <netdb.h>

#define MAXLINE 1000
#define SA struct sockaddr

#define DOCUMENT "index.html"

sigchld_handler(int s)
     while (wait(NULL) > 0);
send_doc(int connfd)
     FILE *fp;
     char output[1000];
     int len;
     if((fp = fopen(DOCUMENT, "r")) == NULL) {
          printf("Cannot open file.\n");
     while(!feof(fp)) {
          fgets(output, 999, fp);
          len = strlen(output);
          if (sendall(connfd, output, &len) == -1) {
               printf("We only sent %d bytes because of the error!\n", len);

sendall(int s, char *buf, int *len)
     int             total = 0;
     int             bytesleft = *len;
     int             n;

     while (total < *len) {
          n = send(s, buf + total, bytesleft, 0);
          if (n == -1) {
          total += n;
          bytesleft -= n;
     *len = total;
          return n == -1 ? -1 : 0;

     int             listenfd, connfd;
     pid_t           childpid;
     socklen_t       clilen;
     struct sockaddr_in cliaddr, servaddr;
     struct sigaction sa;
     int             len, yes = 1, sin_size, nbytes;

     char            data[1000];

     if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
     if ((connfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
     if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
     bzero(&servaddr, sizeof(servaddr));
     servaddr.sin_family = AF_INET;
     servaddr.sin_addr.s_addr = INADDR_ANY;
     servaddr.sin_port = htons(8080);

     if (bind(listenfd, (struct sockaddr *) & servaddr, sizeof(struct sockaddr)) == -1) {
     if (listen(listenfd, 10) == -1) {
     sa.sa_handler = sigchld_handler;
     sa.sa_flags = SA_RESTART;
     if (sigaction(SIGCHLD, &sa, NULL) == -1) {
     for (;;) {
          clilen = sizeof(cliaddr);
          if ((connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) == -1) {
          printf("server: got connection from %s\n", inet_ntoa(cliaddr.sin_addr));
          if ((childpid = fork()) == 0) {

It is working properly.  it is displaying index.html as default which is in the root directory. now i want to modify the code so that it can display any requested page stored in the root folder.? how will i do that??
Question by:pritam123456

Accepted Solution

JugglerW earned 43 total points
ID: 11743550
You must read at least the first line of the HTTP request from the client socket.
Line is like: GET /dir1/dir2/file HTTP/1.x (where x is 0 or 1)
You must send back file dir1/dir2/file under your servers root.
But to have a full web server you have to do much, much more.
Look here to get an idea:

Author Comment

ID: 11745063
i dont really understand what you mean. can you write a sample code for me where should i accept the page name.  give me some more clear information please
LVL 45

Assisted Solution

sunnycoder earned 41 total points
ID: 11745507

Are you familiar with HTTP header format? If no, then check the link posted by JugglerW. This is the standard which specifies how HTTP works. Understanding of this standard is essential if you want to write a web server.

The header of an HTTP request carries the name of the file that is desired by the client. You need to get this information from the header, locate the file locally. Open it and send it back as HTTP response.

Since this is academic, I would refrain from posting code unless you are through with the format and have attempted in addiing the functionality to your code.

Expert Comment

ID: 11745635
In your code:

send_doc(int connfd)
     FILE *fp;
     char output[1000];
     int len;

read one line (terminated by \r\n)  from the socket with handle connfd. This line is in the format I've descibed above.
Then extract the file name and send file back as you've done with index.html.
E.g. if the line is
GET / HTTP/1.x
this is a special case meaning to send index.html in the root dir.
GET / HTTP/1.x
Means to send back file in your servers root dir.

But as sunnycoder say. First glance through the RFC doc to get an idea what the HTTP protocol demands.


Assisted Solution

adg080898 earned 41 total points
ID: 11749374
The program does not receive anything. You need to receive the request to know what the user wants.

First, you have to parse the request. The user might send something like this:

GET /somedir/somefile.htm HTTP/1.1
User-agent: ..whatever...
Accept: */*
Accept-encoding: deflate/gzip
SomeOtherHeader: someothervalue
AnotherHeader: etc.

Each line will end with \r\n, or more exactly, ASCII value 13 followed by ASCII value 10.
(A robust server should also allow lines to end with JUST \r or JUST \n, but it is not entirely necessary).

Headers also allow line continuations: if the first character on a line is a space, then it is a continuation of the previous line.

To keep it simple, accumulate received data into a buffer. Whenever you append received data, search the buffer for an occurrence of "\r\n\r\n". This marks the end of the request.

Once you have found the end of the request, work your way through the request:
- Search for \r (the ASCII value 10).
- Overwrite the found character with a null terminator.
- The beginning of the buffer is now a null terminated string, in my example, "GET /somedir/somefile.htm HTTP/1.1"

If you plan to support more than simply getting a page, you need to process the rest of the request.

To support line continuations, search for an occurrence of \r\n followed by a space. Replace the \r\n with two spaces in all these cases.

Now, create a pointer array which will be filled with pointers to the beginning of each line of the request.

Search for the first occurrence of "\r" and overwrite it with a null terminator.
Then search within the string you just terminated for a ":". Place a null terminator after the colon. The text after the null terminator is the value. The text at the beginning of the line is the name of the header value.

So in my example, you place a null terminator where I have marked it with an X:
User-agent: ..whatever...X
Accept: */*X
Accept-encoding: deflate/gzipX
SomeOtherHeader: someothervalueX
AnotherHeader: etc.X

Then you process through each of those strings and place more terminators, also marked with X:


Now you have chopped the request up into "name" "value" pairs. Fill your pointer array with a pointer to the beginning of each line of the request. Calculate your pointers to where I marked it with a P. I also show all null terminators with X:


Say you need to get the "Accept-encoding" header, you can search your pointer array for the string "Accept-encoding:". Then, to get the value for accept encoding:

char *pHdrLines[MAX_HDR_LINES], *pHdrValue;

for (i = 0; i < nHdrLines; i++) {
    if (strcmp(pHdrLines[i], "Accept-encoding:") == 0) {
        pHdrValue = pHdrLines + strlen(pHdrLines) + 1;
if (i < nHdrLines) {
    // I found it. The name is pHdrLines[i] and the value is at pHdrValue.
    // ...

See? An overview of the process:
- Search for all occurrences of "\r\n " (CR, LF, Space) and replace them with "   " (3 spaces).
- Work your way through the buffer, terminating at each "\r" encountered. Save a pointer to the beginning of that line.
- Once you have terminated each line and populated your pointer array, search each row for a ":" and place a null terminator after it.
- At this point, you have chopped the request into easy-to-process pieces, you can retrieve information from the header using the loop shown above.

You can read ALL the details about how to do this and what all the values mean at the URL JugglerW posted.


Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Windows Batch File - Display current time and date in FOR command 8 81
Apps blocked by Java 9 81
simplest php form 3 79
What does != "" mean in programming 8 35
Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question