Planning network stack development
I should check what environment the user is working in, like bare metal or userspace, but they didn’t specify. I’ll assume a common setup: Linux userspace with a TAP device, as that's straightforward.
The goal is to create a TCP/IP network stack in C. I’ll break it down into clear steps. First, I’ll clarify the scope, focusing on Ethernet, ARP, IPv4, ICMP, and UDP, while briefly describing TCP. Next, I'll outline the architecture and provide code skeletons, followed by an example main program that interacts with the TAP device.Detailing the network stack
I need to maintain a verbosity level of 2: somewhat concise with moderate detail for this large request. I can present it as a "minimal example to build on," noting that it's not production quality. Implementing a network stack from scratch is complex, so I might suggest considering alternatives like lwIP for production use.
Since the user wants an educational approach, I’ll mention that Linux is a common OS. I’ll include the entire netstack.c file with necessary definitions and functions, aiming for around 400-600 lines. However, I need to ensure things like header correctness and checksum calculations, focusing on IPv4 and ICMP ping since that's simpler.Outlining network stack implementation
Given our time, I’m thinking of implementing several important structures like struct eth_hdr, arp_hdr, ipv4_hdr, icmp_hdr, udp_hdr, and tcp_hdr, although we might not fully utilize TCP. I’ll also provide some functions like uint16_t checksum(void *buf, size_t len) and a TAP device open function, tap_alloc.
For the ARP table, I could use a simple array. When receiving a frame, I'll parse the ethertype: for ARP requests to our IP, I’ll send an ARP reply. For IPv4, if there’s an ICMP echo request, I’ll respond. UDP requests will be handled minimally, and while the TCP stack is complex, I could outline a minimal version that covers handshakes and a single connection without retransmissions. However, the full reliable TCP might be omitted due to length constraints. The user seems to be looking for a balance between clear code and high-level overviews, especially since the prompt asks for creating a network stack.Structuring the network stack response
Following the OpenAI specification, I aim for a mid-level response that's concise but not minimal, especially since this question is quite complex. I could design my answer in several sections:
- Requirements & Approach
- Packet Structures
- Core Utilities
- Link Layer Code (TAP device)
- ARP
- IPv4 & ICMP
- UDP
- A sketch of the TCP module, including the state machine
- Build & Run Instructions
Although the user didn't specifically request explanations, I'll need some to ensure clarity. Since I shouldn't ask clarifying questions, I'll aim for a thorough answer, particularly considering usage of the TAP device under Linux and utilizing ioctl TUNSETIFF to set it up and attach it with an IP.Implementing TAP device and headers
I'm outlining a function to allocate a TAP device. It involves opening /dev/net/tun, setting up the device attributes, and using ioctl TUNSETIFF. We should advise compiling with -Wall -O2 and instruct users on creating a TAP device manually or automatically. They’ll need to assign IPs like 10.0.0.1 to the host and 10.0.0.2 to the stack.
I’ll define packet structures including Ethernet, ARP, IPv4, ICMP, UDP, and a minimal TCP header, ensuring to handle checksums appropriately. Though UDP and TCP will require pseudo-headers, I’ll focus primarily on IP and ICMP.
We’ll also configure ARP tables, define functions for sending frames, and implement reading from the TAP device. In the main loop, I’ll ensure we handle Ethernet frames correctly and manage ARP requests and responses. For testing, I'll guide the user to run a ping command to verify functionality.Designing a minimal TCP implementation
I’m thinking about how to approach the TCP aspect of the stack. I can outline a high-level design for the TCP state machine and provide skeleton code for processing TCP segments. The initial handshake will involve sending a SYN to port 7, receiving a SYN-ACK, and then echoing payloads.
For the TCP connection structure, I’ll define a struct to keep track of connection states like LISTEN, SYN_RECEIVED, and ESTABLISHED. Each incoming segment will be processed based on the source IP and port. I'll focus on the flow of states during the handshake, ensuring that we can handle sequence numbers accurately.
The TCP checksum computation is important, so I’ll define a pseudo header and provide a function for this. However, I might simplify by omitting full reliability features like retransmissions, keeping it educational.
To present the implementation clearly, I’ll create a self-contained file that contains ARP, IP, ICMP, and a partial TCP handshake, labeling it as a minimal educational stack. I want to make sure it’s manageable in size while covering essential components properly.Structuring a minimal network stack
I'm developing a minimal IPv4/ARP/ICMP stack specifically for Linux. I’ll include essential headers, define constants for Ethernet protocols, and set up macros for the local IP and MAC addresses.
I'll implement a function for opening a TUN/TAP interface, with instructions for IP configuration. The core logic will include handling ARP requests, sending replies, and managing IPv4 packets efficiently. I plan to use detailed comments within the code to guide the user through the process.
The ICMP echo handling will involve modifying the packet in place and recalculating checksums before sending it back. This way, I can keep the implementation educational yet functional!Implementing checksum and tap functions
I'm defining a checksum function that processes data in big-endian format, ensuring it's suitable for network order, which is key for IPv4 headers. Next, I’ll implement the tap_alloc function to create a TUN interface. I’ll make sure to handle any errors and initialize the interface correctly.
Once the program runs, it needs to configure the TUN interface and set the IP address separately. I’ll highlight that users should send ARP requests, allowing the host to communicate with my stack. After I get this foundation, I’ll then plan to incorporate a minimal TCP skeleton to expand functionality! Below is a minimal, educational TCP/IP-style stack core in C, implementing:
- Ethernet
- ARP (reply to ARP requests)
- IPv4
- ICMP echo (ping replies)
It runs in user space on Linux using a TAP interface.
After that, I’ll show how you would extend this skeleton toward TCP (state machine, checksums, etc.).
This is not production‑ready TCP/IP; it’s a compact starting point you can study and extend.
1. Minimal stack: Ethernet + ARP + IPv4 + ICMP (ping)
File: mini_stack.c
// mini_stack.c - minimal userspace Ethernet/ARP/IPv4/ICMP stack using Linux TAP
// Build: gcc -Wall -O2 mini_stack.c -o mini_stack
// Run as root (or with CAP_NET_ADMIN)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/if_tun.h>
#include <net/if.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <time.h>
#include <unistd.h>
#define BUF_SIZE 2000
// Protocol types
#define ETH_P_IP 0x0800
#define ETH_P_ARP 0x0806
// ICMP types
#define ICMP_ECHO_REQUEST 8
#define ICMP_ECHO_REPLY 0
// Our configuration
#define LOCAL_IP_STR "10.0.0.2" // IP of this stack
static uint8_t LOCAL_MAC[6] = {0x02,0x00,0x00,0x00,0x00,0x02}; // MAC of this stack
static uint32_t local_ip; // network byte order
// ---- Packed headers --------------------------------------------------------
struct eth_hdr {
uint8_t dst[6];
uint8_t src[6];
uint16_t ethertype;
} __attribute__((packed));
struct arp_hdr {
uint16_t htype;
uint16_t ptype;
uint8_t hlen;
uint8_t plen;
uint16_t oper;
uint8_t sha[6];
uint8_t spa[4];
uint8_t tha[6];
uint8_t tpa[4];
} __attribute__((packed));
struct ipv4_hdr {
uint8_t ver_ihl; // version (4 bits) + IHL (4 bits)
uint8_t tos;
uint16_t tot_len;
uint16_t id;
uint16_t frag_off;
uint8_t ttl;
uint8_t proto;
uint16_t checksum;
uint32_t saddr;
uint32_t daddr;
} __attribute__((packed));
struct icmp_hdr {
uint8_t type;
uint8_t code;
uint16_t checksum;
uint16_t id;
uint16_t seq;
} __attribute__((packed));
// ---- Utility: 16-bit Internet checksum ------------------------------------
static uint16_t csum16(const void *data, size_t len)
{
const uint8_t *p = data;
uint32_t sum = 0;
while (len > 1) {
sum += ((uint16_t)p[0] << 8) | p[1];
p += 2;
len -= 2;
}
if (len == 1) {
sum += ((uint16_t)p[0] << 8);
}
while (sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
return (uint16_t)~sum;
}
// ---- TAP device setup ------------------------------------------------------
static int tap_alloc(char *ifname) // ifname has space for IFNAMSIZ
{
struct ifreq ifr;
int fd = open("/dev/net/tun", O_RDWR);
if (fd < 0) {
perror("open(/dev/net/tun)");
exit(1);
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI; // TAP (Ethernet frames), no extra header
if (ifname && *ifname)
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
if (ioctl(fd, TUNSETIFF, (void *)&ifr) < 0) {
perror("ioctl(TUNSETIFF)");
close(fd);
exit(1);
}
if (ifname)
strncpy(ifname, ifr.ifr_name, IFNAMSIZ);
return fd;
}
// ---- ICMP handling ---------------------------------------------------------
static void send_icmp_echo_reply(int fd,
uint8_t *frame,
ssize_t frame_len,
struct eth_hdr *eth,
struct ipv4_hdr *ip,
struct icmp_hdr *icmp,
size_t icmp_len)
{
// Swap Ethernet addresses
uint8_t tmp_mac[6];
memcpy(tmp_mac, eth->src, 6);
memcpy(eth->src, eth->dst, 6);
memcpy(eth->dst, tmp_mac, 6);
// Swap IP addresses
uint32_t tmp_ip = ip->saddr;
ip->saddr = ip->daddr;
ip->daddr = tmp_ip;
// Turn request into reply
icmp->type = ICMP_ECHO_REPLY;
icmp->code = 0;
icmp->checksum = 0;
icmp->checksum = csum16(icmp, icmp_len);
// Recompute IPv4 header checksum
ip->checksum = 0;
uint8_t ihl = (ip->ver_ihl & 0x0F) * 4;
ip->checksum = csum16(ip, ihl);
// Send whole frame back
ssize_t to_write = sizeof(struct eth_hdr) + ntohs(ip->tot_len);
if (to_write > frame_len)
to_write = frame_len; // paranoia
if (write(fd, frame, to_write) < 0) {
perror("write(ICMP reply)");
}
}
static void handle_icmp(int fd,
uint8_t *frame,
ssize_t frame_len,
struct eth_hdr *eth,
struct ipv4_hdr *ip,
uint8_t *payload,
size_t payload_len)
{
if (payload_len < sizeof(struct icmp_hdr))
return;
struct icmp_hdr *icmp = (struct icmp_hdr *)payload;
if (icmp->type != ICMP_ECHO_REQUEST)
return;
// Optional: verify ICMP checksum (omitted for brevity)
send_icmp_echo_reply(fd, frame, frame_len, eth, ip, icmp, payload_len);
}
// ---- ARP handling ----------------------------------------------------------
static void send_arp_reply(int fd,
const struct eth_hdr *req_eth,
const struct arp_hdr *req_arp)
{
uint8_t buf[sizeof(struct eth_hdr) + sizeof(struct arp_hdr)];
struct eth_hdr *eth = (struct eth_hdr *)buf;
struct arp_hdr *arp = (struct arp_hdr *)(buf + sizeof(struct eth_hdr));
memcpy(eth->dst, req_eth->src, 6);
memcpy(eth->src, LOCAL_MAC, 6);
eth->ethertype = htons(ETH_P_ARP);
arp->htype = htons(1); // Ethernet
arp->ptype = htons(ETH_P_IP); // IPv4
arp->hlen = 6;
arp->plen = 4;
arp->oper = htons(2); // reply
memcpy(arp->sha, LOCAL_MAC, 6);
memcpy(arp->spa, &local_ip, 4);
memcpy(arp->tha, req_arp->sha, 6);
memcpy(arp->tpa, req_arp->spa, 4);
if (write(fd, buf, sizeof(buf)) < 0) {
perror("write(ARP reply)");
}
}
static void handle_arp(int fd, uint8_t *frame, ssize_t len)
{
if (len < (ssize_t)(sizeof(struct eth_hdr) + sizeof(struct arp_hdr)))
return;
struct eth_hdr *eth = (struct eth_hdr *)frame;
struct arp_hdr *arp = (struct arp_hdr *)(frame + sizeof(struct eth_hdr));
if (ntohs(arp->htype) != 1 || ntohs(arp->ptype) != ETH_P_IP)
return;
if (arp->plen != 4 || arp->hlen != 6)
return;
uint16_t oper = ntohs(arp->oper);
if (oper == 1) { // ARP request
if (memcmp(arp->tpa, &local_ip, 4) == 0) {
send_arp_reply(fd, eth, arp);
}
} else if (oper == 2) {
// ARP reply: in a full stack you'd cache sender for outbound packets.
}
}
// ---- IPv4 handling ---------------------------------------------------------
static void handle_ipv4(int fd, uint8_t *frame, ssize_t len)
{
if (len < (ssize_t)(sizeof(struct eth_hdr) + sizeof(struct ipv4_hdr)))
return;
struct eth_hdr *eth = (struct eth_hdr *)frame;
struct ipv4_hdr *ip = (struct ipv4_hdr *)(frame + sizeof(struct eth_hdr));
if ((ip->ver_ihl >> 4) != 4)
return; // not IPv4
uint8_t ihl = (ip->ver_ihl & 0x0F) * 4;
if (ihl < sizeof(struct ipv4_hdr))
return;
uint16_t tot_len = ntohs(ip->tot_len);
if (tot_len < ihl || (sizeof(struct eth_hdr) + tot_len) > (size_t)len)
return;
// Only respond to packets addressed to us
if (ip->daddr != local_ip)
return;
uint8_t *payload = ((uint8_t *)ip) + ihl;
size_t payload_len = tot_len - ihl;
switch (ip->proto) {
case 1: // ICMP
handle_icmp(fd, frame, len, eth, ip, payload, payload_len);
break;
default:
// Ignore other protocols (TCP, UDP, etc.) in this minimal example
break;
}
}
// ---- Main loop -------------------------------------------------------------
int main(void)
{
// Parse and store our local IP
struct in_addr addr;
if (inet_aton(LOCAL_IP_STR, &addr) == 0) {
fprintf(stderr, "Invalid LOCAL_IP_STR: %s\n", LOCAL_IP_STR);
return 1;
}
local_ip = addr.s_addr;
// Allocate TAP interface
char ifname[IFNAMSIZ] = "tap0";
int fd = tap_alloc(ifname);
printf("Created/using TAP interface: %s\n", ifname);
printf("Now configure it from another shell, e.g.:\n");
printf(" ip addr add 10.0.0.1/24 dev %s\n", ifname);
printf(" ip link set %s up\n", ifname);
printf("Then: ping %s -I %s\n\n", LOCAL_IP_STR, ifname);
uint8_t buf[BUF_SIZE];
while (1) {
ssize_t n = read(fd, buf, sizeof(buf));
if (n < 0) {
if (errno == EINTR)
continue;
perror("read");
break;
}
if (n < (ssize_t)sizeof(struct eth_hdr))
continue;
struct eth_hdr *eth = (struct eth_hdr *)buf;
uint16_t ethertype = ntohs(eth->ethertype);
switch (ethertype) {
case ETH_P_ARP:
handle_arp(fd, buf, n);
break;
case ETH_P_IP:
handle_ipv4(fd, buf, n);
break;
default:
// Ignore other Ethernet types
break;
}
}
close(fd);
return 0;
}
2. How to build and test
- Build:
gcc -Wall -O2 mini_stack.c -o mini_stack
- Run as root (or with
CAP_NET_ADMIN):
sudo ./mini_stack
It will create a TAP interface (by default tap0) and print setup instructions like:
Created/using TAP interface: tap0
Now configure it from another shell, e.g.:
ip addr add 10.0.0.1/24 dev tap0
ip link set tap0 up
Then: ping 10.0.0.2 -I tap0
- In another terminal:
sudo ip addr add 10.0.0.1/24 dev tap0
sudo ip link set tap0 up
ping 10.0.0.2 -I tap0
You should see successful pings. The kernel sends:
- ARP request for 10.0.0.2 → our stack replies.
- ICMP echo request → our stack replies.
This demonstrates a tiny, working IP stack.
3. Extending this toward a real TCP/IP stack
To turn this into a more complete TCP/IP stack, you’d incrementally add:
3.1. UDP
struct udp_hdr {
uint16_t src_port;
uint16_t dst_port;
uint16_t len;
uint16_t checksum;
} __attribute__((packed));
- In
handle_ipv4, if ip->proto == 17 (UDP):
- Parse the UDP header.
- (Optionally) verify/check the UDP checksum (requires IPv4 pseudo‑header).
- Implement simple handlers, e.g.:
- DNS stub
- Syslog, echo, etc.
3.2. Outbound IP + ARP cache
Right now, the code only replies to inbound packets. For full TCP/UDP you need:
- An ARP cache (
struct arp_entry { uint32_t ip; uint8_t mac[6]; time_t added; }).
- Functions:
int arp_lookup(uint32_t ip, uint8_t mac_out[6]);
void arp_insert(uint32_t ip, const uint8_t mac[6]);
- An
ip_send() that:
- Looks up destination MAC from ARP cache.
- If missing, sends ARP request and queues the IP packet (or drops, in a simple implementation).
- Builds Ethernet + IPv4 header and writes frame to TAP.
3.3. TCP core: state machine + checksum
A bare‑bones TCP implementation needs:
- Connection table
enum tcp_state {
TCP_CLOSED,
TCP_LISTEN,
TCP_SYN_RCVD,
TCP_ESTABLISHED,
TCP_FIN_WAIT_1,
TCP_FIN_WAIT_2,
TCP_CLOSE_WAIT,
TCP_LAST_ACK,
TCP_TIME_WAIT
};
struct tcp_conn {
bool used;
enum tcp_state state;
uint32_t local_ip;
uint16_t local_port;
uint32_t remote_ip;
uint16_t remote_port;
uint32_t snd_una; // oldest unacknowledged seq
uint32_t snd_nxt; // next sequence to send
uint32_t rcv_nxt; // next sequence expected from peer
// You can add windows, retransmission timers, etc.
};
- TCP header
struct tcp_hdr {
uint16_t src_port;
uint16_t dst_port;
uint32_t seq;
uint32_t ack_seq;
uint8_t data_offset_reserved; // high 4 bits: header len / 4
uint8_t flags;
uint16_t window;
uint16_t checksum;
uint16_t urg_ptr;
} __attribute__((packed));
// Flags bits: 0x01 FIN, 0x02 SYN, 0x04 RST, 0x08 PSH, 0x10 ACK, 0x20 URG
- TCP checksum with pseudo‑header
static uint16_t tcp_checksum(const struct ipv4_hdr *ip,
const struct tcp_hdr *tcp,
const uint8_t *payload,
size_t tcp_len) // header + payload
{
uint32_t sum = 0;
// Pseudo-header
const uint8_t *s = (const uint8_t *)&ip->saddr;
const uint8_t *d = (const uint8_t *)&ip->daddr;
sum += ((uint16_t)s[0] << 8) | s[1];
sum += ((uint16_t)s[2] << 8) | s[3];
sum += ((uint16_t)d[0] << 8) | d[1];
sum += ((uint16_t)d[2] << 8) | d[3];
sum += htons(ip->proto);
sum += htons((uint16_t)tcp_len);
// TCP header + payload
const uint8_t *p = (const uint8_t *)tcp;
size_t len = tcp_len;
while (len > 1) {
sum += ((uint16_t)p[0] << 8) | p[1];
p += 2;
len -= 2;
}
if (len == 1) {
sum += ((uint16_t)p[0] << 8);
}
while (sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
return (uint16_t)~sum;
}
- State transitions (very simplified)
In handle_ipv4, when ip->proto == 6 (TCP):
- Parse TCP header (respecting data offset).
- Find existing connection in your table
(local_ip, local_port, remote_ip, remote_port).
- If not found and
SYN + !ACK:
- If
dst_port is one of your “listening” ports:
- Allocate a connection
TCP_SYN_RCVD.
- Choose initial send sequence
snd_nxt = ISS (anything).
- Set
rcv_nxt = seq + 1.
- Send
SYN+ACK segment.
- If in
TCP_SYN_RCVD and you get a segment with ACK acknowledging your SYN:
- Transition to
TCP_ESTABLISHED.
- In
TCP_ESTABLISHED:
- For in-order data:
rcv_nxt += data_len, send ACK.
- For
FIN: advance rcv_nxt, send ACK, and move to close states.
A very minimal echo‑style server on one port could:
- Accept connection (SYN → SYN/ACK → ACK).
- For each data segment received:
- Immediately send it back (with proper seq/ack numbers).
- Ignore retransmission timers, out‑of‑order segments, etc. (OK for a lab toy, not real networks).
4. Where to go from here
To grow this into a more realistic TCP/IP stack you’d add, in roughly this order:
- Checksumming everywhere (verify inbound, compute outbound).
- IP fragmentation / reassembly (or at least dropping fragments explicitly).
- TCP retransmission timers, congestion/window control, and out‑of‑order queues.
- Routing table (multiple interfaces, default route).
- Socket‑like API atop your TCP/UDP (e.g.
my_listen, my_accept, my_send, my_recv).
If you’d like, I can next:
- Add UDP echo support to the sample, or
- Sketch a small but working TCP “handshake + one request” implementation on top of this skeleton.