Contemplating the Challenge
I'm focused on the core request: building a TCP/IP network stack in C. My initial analysis is underway, dissecting the goal, the constraints (C language), and the underlying intent (technical education). The complexity of the project is clear.
Refining the Approach
I'm now prioritizing the essential components. A TAP interface seems the most suitable for interaction. I plan to handle Ethernet, ARP, and IP layers, aiming for ICMP (ping) functionality as a primary demonstration. Given the scope, full TCP/UDP is currently out of reach, but I'll try to showcase their header structures.
Mapping Out Implementation
I'm now detailing the setup steps for the TAP interface, essential for capturing and sending network packets. After that, I will define the Ethernet, IP, and ICMP header structures in C. I intend to provide a functional foundation, including checksum calculations, and a simplified main loop.
Implementing Core Structures
My current focus involves sketching the essential header structures in C: Ethernet, IP, and ICMP. I'm prioritizing accuracy for these, as they're the building blocks. I'm now drafting the ARP reply logic to allow the host to ping the user space stack. I am also detailing the fundamental functions for sending and receiving packets.
Initializing Packet Processing
I'm now writing the core of the packet processing loop. I'll read packets from the TAP interface, parse Ethernet, then IP, before handling ARP and ICMP Echo requests/replies. I'm focusing on simplicity, prioritizing a functional ping response as the first goal.
Codifying Packet Handling
I'm presently building the read and write functions that handle packets to and from the TAP interface. The central loop is forming, and the initial test case will be a ping. Next is refining the Ethernet, IP, and ICMP headers and associated functions, including checksum calculations, which are crucial for network functionality.
Implementing a full TCP/IP stack is a significant undertaking that forms the backbone of the internet. To do this "from scratch" in userspace (without modifying kernel code), the standard approach is to use a TAP interface. A TAP interface allows your program to act like a network interface card (NIC). The OS sends network frames to your program, and your program writes frames back to the OS.
Below is a foundational implementation in C. This code implements enough of the stack to respond to a Ping (ICMP Echo Request) and handle ARP (Address Resolution Protocol), which is required to map IPs to MAC addresses.
The Conceptual Layers
- Link Layer (L2): Ethernet frames.
- Network Layer (L3): IP (Internet Protocol) and ARP.
- Transport Layer (L4): ICMP (Technically L3 helper, but sits inside IP).
C Implementation
Save this as microstack.c.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <arpa/inet.h>
#include <stdint.h>
#define BUF_SIZE 1500
#define TAP_NAME "tap0"
// --- Protocol Constants ---
#define ETH_P_IP 0x0800
#define ETH_P_ARP 0x0806
#define ARP_OP_REQUEST 1
#define ARP_OP_REPLY 2
#define ICMP_TYPE_ECHO_REQ 8
#define ICMP_TYPE_ECHO_REPLY 0
// --- Struct Definitions ---
// Ethernet Header (14 bytes)
struct eth_hdr {
uint8_t dmac[6];
uint8_t smac[6];
uint16_t ethertype;
} __attribute__((packed));
// ARP Header (28 bytes)
struct arp_hdr {
uint16_t hw_type;
uint16_t proto_type;
uint8_t hw_len;
uint8_t proto_len;
uint16_t opcode;
uint8_t smac[6];
uint32_t sip;
uint8_t dmac[6];
uint32_t dip;
} __attribute__((packed));
// IP Header (20 bytes)
struct ip_hdr {
uint8_t ihl : 4;
uint8_t version : 4;
uint8_t tos;
uint16_t len;
uint16_t id;
uint16_t frag_offset;
uint8_t ttl;
uint8_t proto;
uint16_t csum;
uint32_t sip;
uint32_t dip;
} __attribute__((packed));
// ICMP Header
struct icmp_hdr {
uint8_t type;
uint8_t code;
uint16_t csum;
uint16_t id;
uint16_t seq;
} __attribute__((packed));
// --- Helper Functions ---
// Standard Internet Checksum Algorithm
uint16_t checksum(void *addr, int count) {
register uint32_t sum = 0;
uint16_t *ptr = addr;
while (count > 1) {
sum += *ptr++;
count -= 2;
}
if (count > 0)
sum += *(uint8_t *)ptr; // Add left-over byte
while (sum >> 16)
sum = (sum & 0xffff) + (sum >> 16);
return ~sum;
}
// Open a TUN/TAP device
int tun_alloc(char *dev) {
struct ifreq ifr;
int fd, err;
if ((fd = open("/dev/net/tun", O_RDWR)) < 0) {
perror("Cannot open /dev/net/tun");
return fd;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI; // TAP device, no Packet Info
if (*dev) strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if ((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) {
perror("ioctl(TUNSETIFF)");
close(fd);
return err;
}
return fd;
}
// --- Packet Handlers ---
void handle_arp(int tap_fd, struct eth_hdr *eth, struct arp_hdr *arp) {
if (ntohs(arp->opcode) == ARP_OP_REQUEST) {
printf("[ARP] Replying to ARP Request for IP: %s\n", inet_ntoa(*(struct in_addr*)&arp->dip));
// Prepare ARP Reply
arp->opcode = htons(ARP_OP_REPLY);
// Target MAC becomes Source MAC
memcpy(arp->dmac, arp->smac, 6);
// Address of this interface (faked as 00:00:00:00:00:01)
// In a real stack, you'd use your configured MAC
uint8_t my_mac[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
memcpy(arp->smac, my_mac, 6);
// Swap IPs
uint32_t temp_ip = arp->sip;
arp->sip = arp->dip;
arp->dip = temp_ip;
// Ethernet Frame prep
memcpy(eth->dmac, arp->dmac, 6);
memcpy(eth->smac, arp->smac, 6);
// Send
write(tap_fd, eth, 42); // 14 (Eth) + 28 (Arp)
}
}
void handle_icmp(int tap_fd, struct eth_hdr *eth, struct ip_hdr *ip, struct icmp_hdr *icmp, int len) {
if (icmp->type == ICMP_TYPE_ECHO_REQ) {
printf("[ICMP] PING! Replying to %s\n", inet_ntoa(*(struct in_addr*)&ip->sip));
// 1. Modify ICMP Layer
icmp->type = ICMP_TYPE_ECHO_REPLY;
icmp->csum = 0;
icmp->csum = checksum(icmp, len - sizeof(struct eth_hdr) - sizeof(struct ip_hdr));
// 2. Modify IP Layer
uint32_t tmp_ip = ip->sip;
ip->sip = ip->dip;
ip->dip = tmp_ip;
ip->csum = 0;
ip->csum = checksum(ip, sizeof(struct ip_hdr));
// 3. Modify Ethernet Layer
uint8_t tmp_mac[6];
memcpy(tmp_mac, eth->smac, 6);
memcpy(eth->smac, eth->dmac, 6);
memcpy(eth->dmac, tmp_mac, 6);
// 4. Send back
write(tap_fd, eth, len);
}
}
// --- Main Loop ---
int main() {
char dev[IFNAMSIZ] = TAP_NAME;
int tap_fd;
char buffer[BUF_SIZE];
// 1. Connect to kernel network stack
if ((tap_fd = tun_alloc(dev)) < 0) {
return 1;
}
printf("Interface %s created. Configure it now!\n", dev);
printf("Run: sudo ip addr add 10.0.0.1/24 dev tap0\n");
printf("Run: sudo ip link set tap0 up\n");
printf("Then try: ping 10.0.0.2\n\n");
while (1) {
ssize_t nread = read(tap_fd, buffer, sizeof(buffer));
if (nread < 0) {
perror("Read from interface");
close(tap_fd);
exit(1);
}
struct eth_hdr *eth = (struct eth_hdr *)buffer;
// Parse Ethernet Protocol
if (ntohs(eth->ethertype) == ETH_P_ARP) {
struct arp_hdr *arp = (struct arp_hdr *)(buffer + sizeof(struct eth_hdr));
handle_arp(tap_fd, eth, arp);
}
else if (ntohs(eth->ethertype) == ETH_P_IP) {
struct ip_hdr *ip = (struct ip_hdr *)(buffer + sizeof(struct eth_hdr));
// If Protocol is ICMP (1)
if (ip->proto == 1) {
struct icmp_hdr *icmp = (struct icmp_hdr *)(buffer + sizeof(struct eth_hdr) + sizeof(struct ip_hdr));
handle_icmp(tap_fd, eth, ip, icmp, nread);
}
}
}
return 0;
}
How to Run This
This program acts as the device 10.0.0.2. You will configure your actual OS to be 10.0.0.1.
-
Compile:
gcc microstack.c -o microstack
-
Run (requires root for network access):
sudo ./microstack
-
Configure the Interface (In a new terminal):
When you run the program, it creates tap0. You need to assign an address to your Linux kernel side of that interface so it can talk to your C program:
# Set the kernel's IP on this virtual cable
sudo ip addr add 10.0.0.1/24 dev tap0
# Turn the interface on
sudo ip link set tap0 up
-
Test with Ping:
Now try to ping an address inside the subnet, but not the kernel's own address. Your C program will reply.
# Ping the virtual device (your C program)
ping 10.0.0.2
How it Works
- TUN/TAP: We use
ioctl to create tap0. This creates a virtual ethernet cable. One end is plugged into the Linux Kernel, the other end is the file descriptor tap_fd in our C program.
- Ethernet Parsing: When
read() returns, we have raw bytes. We cast the beginning of the buffer to struct eth_hdr. We look at ethertype to decide if it is IP (0x0800) or ARP (0x0806).
- ARP Handling: Before your OS sends a Ping IP packet, it needs the MAC address of
10.0.0.2. It broadcasts an ARP request. Our code catches this, creates an ARP Reply saying "10.0.0.2 is at MAC 00:00:00:00:00:01", and sends it back.
- ICMP Handling: Once the OS knows the MAC, it sends the IP packet (ICMP Echo Request). We parse the IP header, see protocol
1 (ICMP), parse the ICMP header, and modify the buffer in-place to transform the Request into a Reply (swapping source/dest addresses and recalculating checksums).
Next Steps for a Full Stack
To expand this into a full TCP/IP stack, you would implement:
- Routing Table: Logic to determine where to send outgoing packets based on IP subnets.
- TCP State Machine: A large switch statement to handle connection states (
SYN_SENT, ESTABLISHED, FIN_WAIT).
- Sliding Window: Logic to handle TCP sequence numbers, acknowledgments, and retransmissions.
- Socket API: An interface allowing other applications to use your stack.