I have developped this project in order to explore and learn more about how HTTP servers work under the hood. It is written with a focus on simplicity so on HTTP/1.1. I have licensed it under MIT License so feel free to fork it, clone it and remodel it.
HTTP/1.1 : RFC 7230 - RFC 7231 - RFC 7232 - RFC 7233 - RFC 7234 - RFC 7235
A HTTP server has a basic and simple roadmap to follow.
- Listens to a port for incoming HTTP request
In order to answer to incoming HTTP requests, we have to be able to listens to an opened port via a socket to receive the messages. Via this socket, we will also send the responses.
- Create the socket
// In order to create the socket, I used the unix standard library socket. (man socket)
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
- Identify the socket
// The socket is bound to a specific port (I used 4600 by default) using the bind() system call. (man bind)
bind(socket_fd, (struct sockaddr *)&address, address_len);
- On the server, wait for an incoming connection
// Now we have to listen for incoming connections using the listen() system call. (man listen)
listen(socket_fd, LISTEN_BACKLOG);
- Send and receive messages
// Once a connection request is detected on the listened port, we use accept to create a file descriptor and establish the connection. (man accept)
int connection_fd = accept(socket_fd, (struct sockaddr *)&address, &address_len);
// In the first scenario (commit below), I wrote a simple message as a response.
const char *message = "Hello from server!\n";
write(connection_fd, message, strlen(message));
- Close the socket
close(connection_fd);
close(socket_fd);`
For more informations, please check out this commit (file src/main.c) :
- Compiler for C code (if using the C version):
gcc
or equivalent.
-
Clone the repository:
git clone https://github.com/Hugo-CASTELL/http-server.git && cd http-server
-
(Optional) Remove the .git:
rm -r .git
TODO Build
TODO Usage