Making a simple HTTP server with sockets

Neel Somani - October 15, 2017

In this blog post, we’ll set up a very simple server in C. The server will be single-threaded, and it will just write the phrase "Hello world" to the client. The full code is available on GitHub. For context, I’m writing this code on a computer running macOS.

To do so, we’ll open a socket for the server, bind that socket to an address, and listen for client requests. When a client makes a request, we’ll handle it, then close the socket for that client.

Part 1: Setup

Before we open our server socket and start listening for incoming requests, let’s set up the signal handler to make sure that our server always shuts down gracefully. Right now, since there’s no server socket open, this won’t do anything, but it will be helpful as we proceed. We’ll pass the pointer to our server file descriptor to a function that we’ll write soon, which we’ll call start_server.

We initially set up the server socket. Then, we initialize a struct of the type sockaddr_in, since we need to pass it to the bind function. Then, we start listening, establishing a maximum length of backlogged connections at 1024.

In the server loop, rather than creating a socket for clients, we accept connections. We pass the file descriptor to the handle_client function, which we’ll shortly implement.

We start the response by sending a 200 status code, meaning "OK." Then, we declare two mandatory headers, "Content-Type" and "Content-Length." Finally, we write to the client until there’s no more data to write, at which point we return. The server loop closes the client socket.

Conclusion

Now you can compile the code with gcc server.c -o server. Then you can run the server with ./server, and you can direct your browser to http://localhost:8000. You should see "Hello world." printed to your screen.

That’s all there is to it. If you want to expand on this, you might want to handle each client connection on its own thread, so the server doesn’t block. You might also want to incorporate some error handling. There are plenty of improvements that can be made, but this code should get you started pretty quickly.

About the Author

Neel Somani, a student at the University of California, Berkeley, is the founder of Apptic LLC. In addition to computer science, he's interested in philosophy and entrepreneurship. You can follow him on LinkedIn and Twitter.