Linux TCP/IP Programming in C | Generated by AI

Home 2025.11

TCP/IP Protocols in Linux: Overview and Using Them in C

In Linux, the TCP (Transmission Control Protocol) and IP (Internet Protocol) are core networking protocols implemented in the kernel as part of the Linux TCP/IP stack. This stack handles low-level details like packet routing, congestion control, and connection management. User-space applications (e.g., your C programs) interact with this stack via the Berkeley sockets API (also known as POSIX sockets), which provides a standardized way to create network connections.

You don’t need to implement TCP/IP yourself— the kernel does that. Instead, you use the sockets API to “talk” to the kernel. This API is built into the standard C library (glibc) on Linux, so there’s no separate “TCP/IP library” to install or link against. Everything is provided by libc (GNU C Library).

Key Libraries and Headers

No extra flags like -lsocket are needed on Linux (unlike some older Unix systems). Just compile with gcc your_program.c -o your_program.

Basic Example: Simple TCP Client in C

Here’s a minimal TCP client that connects to a server (e.g., port 80 on example.com). This demonstrates using the sockets API.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>  // For close()

int main() {
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);  // Create TCP socket (AF_INET for IPv4, SOCK_STREAM for TCP)
    if (sockfd < 0) {
        perror("socket");
        return 1;
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(80);  // Host-to-network byte order
    inet_pton(AF_INET, "93.184.216.34", &server_addr.sin_addr);  // IP for example.com

    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        perror("connect");
        close(sockfd);
        return 1;
    }

    const char* msg = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    send(sockfd, msg, strlen(msg), 0);

    char buffer[1024];
    int bytes = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
    buffer[bytes] = '\0';
    printf("Response: %s\n", buffer);

    close(sockfd);
    return 0;
}

For a server, you’d use bind(), listen(), and accept() instead of connect().

Where to Learn More

If this isn’t what you meant (e.g., kernel modules or something else), provide more details!


Back

x-ai/grok-4-fast

Donate