How to Create Web Server in C

Faraz

By Faraz -

Learn how to create a web server in C programming. This easy-to-follow guide provides step-by-step instructions to help you build and run a simple http web server.


create-web-htpp-server-in-c.webp

Introduction

Creating a web server in C programming is a fundamental project that helps you understand how servers work and how data is managed over the internet. Whether you're a beginner or an experienced programmer, building a web server from scratch is a valuable exercise to enhance your coding skills and knowledge of networking concepts.

In this guide, we’ll walk you through the entire process of creating a web server in C. By the end of this tutorial, you’ll have a fully functional web server that can handle basic HTTP requests. We’ll break down the code and explain each step in simple terms to make it easy for you to follow along.

Step-by-Step Guide to Create a Web Server in C

Step 1: Setting Up Your Development Environment

Before you start coding, make sure you have the necessary tools:

  • C Compiler: GCC is the most common compiler for C programming.
  • Text Editor: You can use any text editor like Visual Studio Code, Sublime Text, or Notepad++.
  • Terminal: For compiling and running the program.

Make sure your environment is set up correctly, and all tools are properly installed.

Step 2: Create the Basic Server Structure

Start by creating a new C file named web_server.c. In this file, you’ll write the code to initialize and run your server.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>

#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib

#define PORT 8080

int main() {
    WSADATA wsa;
    SOCKET server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    char *hello = "HTTP/1.1 200 OK\nContent-Type: text/html\nContent-Length: 12\n\nHello world";

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    // Create socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Socket creation failed with error : %d", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // Bind socket
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) == SOCKET_ERROR) {
        printf("Bind failed with error code : %d", WSAGetLastError());
        closesocket(server_fd);
        WSACleanup();
        return 1;
    }

    // Listen for incoming connections
    if (listen(server_fd, 3) == SOCKET_ERROR) {
        printf("Listen failed with error code : %d", WSAGetLastError());
        closesocket(server_fd);
        WSACleanup();
        return 1;
    }

    printf("Server is listening on port %d\n", PORT);

    // Accept incoming connection
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, &addrlen)) == INVALID_SOCKET) {
        printf("Accept failed with error code : %d", WSAGetLastError());
        closesocket(server_fd);
        WSACleanup();
        return 1;
    }

    // Read client request
    recv(new_socket, buffer, 1024, 0);
    printf("Received request:\n%s\n", buffer);

    // Send response
    send(new_socket, hello, strlen(hello), 0);
    printf("Response sent\n");

    // Cleanup
    closesocket(new_socket);
    closesocket(server_fd);
    WSACleanup();

    return 0;
}

Step 3: Understanding the Code

  • Including winsock2.h: This header file is necessary for Windows socket programming. It replaces sys/socket.h and other Unix-specific headers.
  • Linking ws2_32.lib: This library is required for socket operations on Windows. The #pragma comment(lib, "ws2_32.lib") line ensures that the necessary library is linked.
  • Initializing Winsock: The WSAStartup() function is used to initialize the Winsock library. It's a necessary step before using any Winsock functions.
  • Cleaning Up: The WSACleanup() function is used to clean up the resources allocated by Winsock after the program is done.

Step 4: Compiling the Program

Once you have written the code, it’s time to compile it. Open your terminal and navigate to the directory where your web_server.c file is located. Run the following command to compile the program:

gcc web_server.c -o web_server -lws2_32

This command tells the GCC compiler to compile web_server.c and generate an executable file named web_server.

Step 5: Running the Program

After successful compilation, you can run the web server using the following command:

web_server.exe

The server will start running and listening for incoming connections on port 8080. You can test the server by opening a web browser and entering http://localhost:8080/ in the address bar. You should see a simple "Hello world" message displayed on the screen.

Compiling and Running the Program

To recap, here’s a quick overview of the process:

  1. Write the Code: Create a C file and write the code to set up the server.
  2. Compile the Program: Use GCC to compile the code into an executable.
  3. Run the Server: Execute the compiled program to start the web server.
  4. Test the Server: Open a web browser and navigate to http://localhost:8080/ to see the output.

Conclusion

Creating a web server in C programming is a rewarding project that provides hands-on experience with networking and socket programming. By following the steps outlined in this guide, you’ve learned how to set up a basic web server that can handle simple HTTP requests.

This foundational knowledge can be expanded upon to build more complex servers with additional features. As you continue to explore C programming, consider experimenting with different aspects of web development, such as handling multiple requests, implementing security features, or building a more sophisticated response mechanism.

By practicing and enhancing your skills, you'll be well on your way to becoming proficient in C programming and web server development.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺