This is a simple HTTP server written in C that listens on a specified port and responds to GET requests. It can serve HTML pages and images.
Here is a list of functions in the server, along with a brief description, return type, and how to call them:
- Initializes the server and binds it to the specified port.
- Returns: 0 on error, socket fd on success
- Call:
int s = srv_init(8080);
- Accepts an incoming connection and returns a new socket fd for the client.
- Returns: 0 on error, new socket fd on success
- Call:
int c = cli_accept(s);
- Parses an HTTP request string and returns a struct containing the method and URL.
- Returns: 0 on error, parsed HTTP request struct on success
- Call:
httpreq *req = parse_http(buffer);
- Reads data from a client socket and returns the received data.
- Returns: 0 on error, received data on success
- Call:
char *p = cli_read(c);
- Sends an HTTP response to a client with the specified content type and data.
- Returns: void
- Call:
http_response(c, "text/html", "<html>...</html>");
- Sends HTTP headers to a client with the specified status code.
- Returns: void
- Call:
http_headers(c, 200);
- Reads a file from disk and returns a struct containing the file data.
- Returns: 0 on error, file struct on success
- Call:
File *f = readfile("example.html");
- Sends a file to a client with the specified content type.
- Returns: 1 on success, 0 on error
- Call:
sendfile(c, "image/png", f);
- Handles a client connection, parsing the request and sending a response.
- Returns: void
- Call:
cli_conn(s, c);
To compile the server, use the following command:
gcc -o httpd httpd.c
To run the server, use the following command:
./httpd <port>
Replace <port>
with the desired port number, such as 8080.
Note
This is a very basic HTTP server and does not support many features, such as POST requests, SSL/TLS, or error handling. It is intended for educational purposes only.