This project is a simple HTTP server implemented in C with the help of the platform CodeCrafters. It handles basic HTTP GET and POST requests and can serve files from a specified directory. The server listens on port 4221 by default.
- Serve static files from a specified directory.
- Handle GET and POST requests.
- Echo responses for specific endpoints.
- Return User-Agent details.
- Allow file uploads via POST requests.
Once you have cloned the repo and are in the project folder, you can compile the server with the following commands.
cd app
gcc server.c -o server
Run the compiled server with an optional --directory argument to specify the root directory for serving files:
./server --directory /path/to/directory
If no directory is specified, the server will use the current directory.
You can test the server using curl. Below are some examples:
- Simple GET Request
curl -v http://localhost:4221/
- Echo Request
curl -v http://localhost:4221/echo/hello
- User-Agent Request
curl -v http://localhost:4221/user-agent
- File Upload
curl -v -X POST http://localhost:4221/files/upload.txt -d 'Hello World'
- File Download
curl -v http://localhost:4221/files/upload.txt
The main function sets up the server, including the following steps:
- Parse command-line arguments to get the directory to serve files from.
- Change the working directory to the specified directory.
- Set up the server socket to listen on port 4221.
- Use setsockopt to set SO_REUSEPORT to avoid "Address already in use" errors.
- Bind the socket to the address and port.
- Listen for incoming connections.
- Accept connections and handle them in a child process using fork.
The handle_connection function processes the client's request and sends an appropriate response:
- Read the request using recv.
- Parse the HTTP method and requested path.
- Handle different paths:
- /: Respond with "200 OK".
- /echo/: Echo the rest of the path.
- /user-agent: Return the User-Agent header.
- /files/ with GET: Serve the requested file.
- /files/ with POST: Save the uploaded content to the specified file.
- Send the response using send.