← Back to list

Building a Simple TCP Web Server in C: A Beginner’s Guide

In this tutorial, we’ll create a basic TCP web server in C that serves an HTML file. You’ll learn the fundamentals of socket programming…

trish · 2025-02-07 16:56 · 9 claps · 3.2 min read paywalled
#c #c-programming #web-server #tutorial #beginners-guide
Open on Medium ↗
Wiki topics: 💻 · Programming 🌐 · Web Development 🔒 · Cybersecurity

Building a Simple TCP Web Server in C: A Beginner’s Guide

In this tutorial, we’ll create a basic TCP web server in C that serves an HTML file. You’ll learn the fundamentals of socket programming, HTTP, and server architecture.

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Theory
  4. Setup
  5. Step-by-Step Implementation
  6. Running the Server
  7. Architecture Diagram
  8. GitHub Repository
  9. Support & Feedback

1. Introduction

A web server listens for incoming client requests (e.g., from browsers) and responds with data like HTML files. We’ll build a minimal server in C to understand how networking fundamentals work at a low level.

2. Prerequisites

  • Basic knowledge of C programming.
  • Familiarity with terminal/command line.
  • A text editor (VS Code, Sublime, etc.).
  • gcc compiler installed.
  • A modern browser for testing.

3. Theory

What is a TCP Server?

  • TCP (Transmission Control Protocol): A connection-oriented protocol that ensures reliable data delivery.
  • Server Workflow:
  1. Bind to a port.
  2. Listen for connections.
  3. Accept connections.
  4. Send/Receive data.
  5. Close connections.

How HTTP Works

  • HTTP is a request-response protocol over TCP.
  • A basic HTTP response looks like:
HTTP/1.1 200 OK 
Content-Type: text/html  

<html>...</html>

4. Setup

Project Structure

tcp-server/
├── index.html       # HTML file to serve
├── webserver.c      # C source code
└── Makefile         # For easy compilation

Create index.html

<!DOCTYPE html>
<html>
<head>
    <title>C Web Server</title>
</head>
<body>
    <h1>Hello from C!</h1>
    <p>A minimal web server written in C.</p>
</body>
</html>

Create Makefile

CC = gcc
CFLAGS = -Wall -Wextra
TARGET = webserver

all: $(TARGET)
$(TARGET): webserver.c
    $(CC) $(CFLAGS) -o $@ $^
run:
    ./$(TARGET)
clean:
    rm -f $(TARGET)

5. Step-by-Step Implementation

Step 1: Include Headers

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
  • Explanation:
  • <stdio.h>: For input/output functions.
  • <stdlib.h>: For memory allocation and program control.
  • <string.h>: For string manipulation.
  • <unistd.h>: For POSIX API (e.g., close()).
  • <arpa/inet.h>: For socket-related functions.

Step 2: Define Constants

#define PORT 8080
#define BUFFER_SIZE 2048
  • Explanation:
  • PORT: The port number the server will listen on.
  • BUFFER_SIZE: The size of the buffer for reading/writing data.

Step 3: Create the Socket

int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
    perror("Socket creation failed");
    exit(EXIT_FAILURE);
}
  • Explanation:
  • socket() creates a TCP socket.
  • AF_INET: IPv4 address family.
  • SOCK_STREAM: TCP socket type.
  • 0: Default protocol.

Step 4: Bind the Socket

struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);

if (bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
    perror("Bind failed");
    close(server_socket);
    exit(EXIT_FAILURE);
}
  • Explanation:
  • bind() associates the socket with a port.
  • INADDR_ANY: Listen on all available interfaces.
  • htons(): Converts port number to network byte order.

Step 5: Listen for Connections

if (listen(server_socket, 5) < 0) {
    perror("Listen failed");
    close(server_socket);
    exit(EXIT_FAILURE);
}
printf("Server listening on port %d...\n", PORT);
  • Explanation:
  • listen() marks the socket as passive to accept connections.
  • 5: Maximum number of pending connections.

Step 6: Accept Connections

struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);

int client_socket = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
if (client_socket < 0) {
    perror("Accept failed");
    continue;
}
printf("Client connected: %s\n", inet_ntoa(client_addr.sin_addr));
  • Explanation:
  • accept() blocks until a client connects.
  • inet_ntoa(): Converts client IP address to a string.

Step 7: Send HTTP Response

void send_html(int client_socket, const char *path) {
    FILE *file = fopen(path, "r");
    if (!file) {
        perror("Failed to open HTML file");
        return;
    }

char buffer[BUFFER_SIZE];
    size_t bytes_read;
    // Send HTTP headers
    char *headers = "HTTP/1.1 200 OK\r\n"
                    "Content-Type: text/html\r\n\r\n";
    send(client_socket, headers, strlen(headers), 0);
    // Send HTML content
    while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) > 0) {
        send(client_socket, buffer, bytes_read, 0);
    }
    fclose(file);
}
  • Explanation:
  • send() sends data to the client.
  • HTTP headers are sent first, followed by the HTML content.

Step 8: Close Connections

close(client_socket);
printf("Client disconnected\n");
  • Explanation:
  • close() terminates the client connection.

6. Running the Server

Compile the code:

make

Run the server:

make run

Open http://localhost:8080 in your browser.

7. Architecture Diagram

+-------------+       +-------------+       +-------------+
|  Client     |       |  Server     |       |  HTML File  |
| (Browser)   | <---> | (TCP Socket)| <---> | (index.html)|
+-------------+       +-------------+       +-------------+

8. GitHub Repository

You can find the full code for this project in the following GitHub repository: **tcp_server_c Repository**

Branch: mini-tcp-server

The code for this specific project is located in the branch mini-tcp-server. To clone the repository and switch to the correct branch, use the following commands:

git clone https://github.com/dexter-xD/tcp_server_c.git
cd tcp_server_c
git checkout mini-tcp-server

This will give you access to the complete source code, including the webserver.c, index.html, and Makefile files.

9. Support & Feedback

Conclusion

You’ve built a minimal TCP web server in C! While this is a basic implementation, it covers core concepts like sockets, binding, and HTTP. To improve it:

  • Add error handling.
  • Support concurrent clients (e.g., using threads).
  • Parse HTTP requests.

Happy coding! 🚀


메타데이터
post_id
43d1d494c6c6
slug
building-a-simple-tcp-web-server-in-c-a-beginners-guide-43d1d494c6c6
url
https://medium.com/@trish07/building-a-simple-tcp-web-server-in-c-a-beginners-guide-43d1d494c6c6
canonical_url
https://medium.com/@trish07/building-a-simple-tcp-web-server-in-c-a-beginners-guide-43d1d494c6c6
author_url
https://medium.com/@trish07
status
ok
fetched_at
2026-06-16 19:09:56