C Tutorial

Implementing a Basic Web Server in C


Introduction

A web server is a program that serves web pages to clients (browsers). This guide explores the fundamentals of implementing a simple web server in C and provides sample code to illustrate key concepts and techniques.

Key Web Server Features

A basic web server should include the following features:

  • HTTP Protocol Support: Handling incoming HTTP requests and sending responses.
  • Static Content Serving: Serving static HTML, CSS, JavaScript, and other files.
  • Dynamic Content Generation: Generating dynamic content through server-side scripting.

Sample Code for a Basic Web Server

Let's create a simple C program that serves static HTML content. We'll use socket programming to listen for incoming HTTP requests and respond with a basic HTML page. Here's a basic example:

// Sample web server in C // (This is a simplified example and not suitable for production use) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> int main() { // Server socket setup int server_socket = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(80); // HTTP port server_address.sin_addr.s_addr = INADDR_ANY; // Bind the server socket bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)); // Listen for incoming connections listen(server_socket, 5); printf(`Web server is running and listening on port 80... `); while (1) { // Accept incoming connections int client_socket = accept(server_socket, NULL, NULL); // Send an HTTP response char response[] = `HTTP/1.1 200 OK Content-Length: 12 Hello, World!`; send(client_socket, response, sizeof(response) - 1, 0); // Close the client socket close(client_socket); } // Close the server socket close(server_socket); return 0; }

This code represents a basic web server in C that listens on port 80 and responds to incoming HTTP requests with a simple `Hello, World!` message. It's a minimal example, and production web servers are much more complex, supporting multiple file types and dynamic content generation.

Conclusion

Implementing a web server in C involves setting up sockets, handling HTTP requests, and responding with appropriate content. This guide introduced the basics of creating a simple web server and provided sample code for static content serving. To build a production-ready web server, consider using established web server libraries and frameworks.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.