Planning minimal ARP-focused TCP/IP skeleton
I'm outlining a Linux C implementation of an ARP cache with entry aging, LRU eviction, and handling ARP requests/replies via raw sockets on a chosen interface. Next, I'll write self-contained code with cache management, interface info retrieval, ARP packet crafting/parsing, and a main loop processing ARP frames.
Below is a self‑contained example in C that shows how you might scaffold a very simple “network stack” focused on ARP resolution. It maintains an ARP cache with entry aging and LRU eviction, and it handles ARP requests/replies on a given interface via a raw socket.
This is not a full TCP/IP stack (that would be thousands of lines of code), but it demonstrates the major moving parts you asked for: parsing ARP packets, sending ARP requests/replies, and maintaining an ARP cache with aging and LRU replacement. You can extend this skeleton with actual IP/TCP handling as needed.
/*
* Minimal ARP handling example on Linux using raw sockets.
* - Maintains an ARP cache with entry aging and LRU eviction
* - Handles ARP requests for the local IP
* - Processes ARP replies to populate the cache
*
* Compile with: gcc -Wall -o arp_demo arp_demo.c
* Run as root: ./arp_demo eth0
*
* This does not implement a full TCP/IP stack, but shows how you can build
* ARP functionality into your own stack.
*/
#include <arpa/inet.h>
#include <errno.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_packet.h>
#include <netinet/ether.h>
#include <netinet/if_ether.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#define ARP_CACHE_SIZE 16
#define ARP_ENTRY_TTL 60 /* seconds before an ARP cache entry expires */
/* Represents one ARP cache entry */
struct arp_entry {
uint32_t ip; /* IPv4 address in network byte order */
uint8_t mac[ETH_ALEN]; /* MAC address */
time_t added; /* time when entry was added */
time_t last_used; /* time when entry was last used */
bool valid;
};
/* ARP cache data structure */
struct arp_cache {
struct arp_entry entries[ARP_CACHE_SIZE];
};
/* Global ARP cache instance */
static struct arp_cache g_arp_cache;
/* Get current timestamp helper */
static inline time_t now(void) {
return time(NULL);
}
/* Initialize ARP cache */
void arp_cache_init(struct arp_cache *cache) {
memset(cache, 0, sizeof(*cache));
}
/* Remove expired entries from ARP cache */
void arp_cache_age(struct arp_cache *cache) {
time_t t = now();
for (int i = 0; i < ARP_CACHE_SIZE; ++i) {
if (cache->entries[i].valid &&
(t - cache->entries[i].added) > ARP_ENTRY_TTL) {
cache->entries[i].valid = false;
}
}
}
/* Lookup MAC address for an IP in the ARP cache.
* Returns true if found (and copies the MAC into out_mac),
* otherwise returns false.
*/
bool arp_cache_lookup(struct arp_cache *cache, uint32_t ip, uint8_t out_mac[ETH_ALEN]) {
arp_cache_age(cache); /* purge expired entries */
for (int i = 0; i < ARP_CACHE_SIZE; ++i) {
if (cache->entries[i].valid && cache->entries[i].ip == ip) {
memcpy(out_mac, cache->entries[i].mac, ETH_ALEN);
cache->entries[i].last_used = now();
return true;
}
}
return false;
}
/* Insert or update an ARP cache entry. If full, evict least-recently-used. */
void arp_cache_insert(struct arp_cache *cache, uint32_t ip, const uint8_t mac[ETH_ALEN]) {
/* Check if already exists -> update */
for (int i = 0; i < ARP_CACHE_SIZE; ++i) {
if (cache->entries[i].valid && cache->entries[i].ip == ip) {
memcpy(cache->entries[i].mac, mac, ETH_ALEN);
cache->entries[i].added = now();
cache->entries[i].last_used = cache->entries[i].added;
return;
}
}
/* Try to find a free slot */
for (int i = 0; i < ARP_CACHE_SIZE; ++i) {
if (!cache->entries[i].valid) {
cache->entries[i].valid = true;
cache->entries[i].ip = ip;
memcpy(cache->entries[i].mac, mac, ETH_ALEN);
cache->entries[i].added = now();
cache->entries[i].last_used = cache->entries[i].added;
return;
}
}
/* Evict LRU entry (smallest last_used) */
int lru_index = 0;
time_t lru_time = cache->entries[0].last_used;
for (int i = 1; i < ARP_CACHE_SIZE; ++i) {
if (cache->entries[i].last_used < lru_time) {
lru_time = cache->entries[i].last_used;
lru_index = i;
}
}
cache->entries[lru_index].valid = true;
cache->entries[lru_index].ip = ip;
memcpy(cache->entries[lru_index].mac, mac, ETH_ALEN);
cache->entries[lru_index].added = now();
cache->entries[lru_index].last_used = cache->entries[lru_index].added;
}
/* Utility: resolve interface MAC and IP */
bool get_interface_info(const char *ifname, uint8_t mac[ETH_ALEN], uint32_t *ip) {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
perror("socket()");
return false;
}
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
/* MAC */
if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
perror("ioctl(SIOCGIFHWADDR)");
close(fd);
return false;
}
memcpy(mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
/* IP */
if (ioctl(fd, SIOCGIFADDR, &ifr) == -1) {
perror("ioctl(SIOCGIFADDR)");
close(fd);
return false;
}
*ip = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr.s_addr;
close(fd);
return true;
}
/* Send an ARP request for target_ip (network byte order) */
void send_arp_request(int sock_fd, const char *ifname,
uint32_t my_ip, const uint8_t my_mac[ETH_ALEN],
uint32_t target_ip) {
uint8_t buffer[42]; // Ethernet (14) + ARP (28)
struct ether_header *eth = (struct ether_header *)buffer;
struct ether_arp *arp = (struct ether_arp *)(buffer + ETH_HLEN);
/* Ethernet header: dst = broadcast, src = my_mac */
memset(eth->ether_dhost, 0xff, ETH_ALEN);
memcpy(eth->ether_shost, my_mac, ETH_ALEN);
eth->ether_type = htons(ETH_P_ARP);
/* ARP header */
arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);
arp->ea_hdr.ar_pro = htons(ETH_P_IP);
arp->ea_hdr.ar_hln = ETH_ALEN;
arp->ea_hdr.ar_pln = 4;
arp->ea_hdr.ar_op = htons(ARPOP_REQUEST);
memcpy(arp->arp_sha, my_mac, ETH_ALEN);
memcpy(arp->arp_spa, &my_ip, 4);
memset(arp->arp_tha, 0x00, ETH_ALEN); /* unknown yet */
memcpy(arp->arp_tpa, &target_ip, 4);
/* Send */
struct sockaddr_ll dst = {0};
dst.sll_family = AF_PACKET;
dst.sll_halen = ETH_ALEN;
dst.sll_protocol = htons(ETH_P_ARP);
dst.sll_ifindex = if_nametoindex(ifname);
memcpy(dst.sll_addr, eth->ether_dhost, ETH_ALEN);
if (sendto(sock_fd, buffer, sizeof(buffer), 0,
(struct sockaddr *)&dst, sizeof(dst)) < 0) {
perror("sendto(arp_request)");
} else {
printf("Sent ARP request for %s\n", inet_ntoa(*(struct in_addr *)&target_ip));
}
}
/* Send an ARP reply to 'target_mac'/'target_ip' telling them our IP/MAC */
void send_arp_reply(int sock_fd, const char *ifname,
uint32_t my_ip, const uint8_t my_mac[ETH_ALEN],
uint32_t target_ip, const uint8_t target_mac[ETH_ALEN]) {
uint8_t buffer[42];
struct ether_header *eth = (struct ether_header *)buffer;
struct ether_arp *arp = (struct ether_arp *)(buffer + ETH_HLEN);
memcpy(eth->ether_dhost, target_mac, ETH_ALEN);
memcpy(eth->ether_shost, my_mac, ETH_ALEN);
eth->ether_type = htons(ETH_P_ARP);
arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);
arp->ea_hdr.ar_pro = htons(ETH_P_IP);
arp->ea_hdr.ar_hln = ETH_ALEN;
arp->ea_hdr.ar_pln = 4;
arp->ea_hdr.ar_op = htons(ARPOP_REPLY);
memcpy(arp->arp_sha, my_mac, ETH_ALEN);
memcpy(arp->arp_spa, &my_ip, 4);
memcpy(arp->arp_tha, target_mac, ETH_ALEN);
memcpy(arp->arp_tpa, &target_ip, 4);
struct sockaddr_ll dst = {0};
dst.sll_family = AF_PACKET;
dst.sll_halen = ETH_ALEN;
dst.sll_protocol = htons(ETH_P_ARP);
dst.sll_ifindex = if_nametoindex(ifname);
memcpy(dst.sll_addr, target_mac, ETH_ALEN);
if (sendto(sock_fd, buffer, sizeof(buffer), 0,
(struct sockaddr *)&dst, sizeof(dst)) < 0) {
perror("sendto(arp_reply)");
} else {
printf("Sent ARP reply to %s\n", ether_ntoa((struct ether_addr *)target_mac));
}
}
/* Handle an incoming ARP packet: request or reply */
void handle_arp_packet(int sock_fd, const char *ifname,
struct ether_arp *arp,
uint32_t my_ip, const uint8_t my_mac[ETH_ALEN]) {
uint16_t op = ntohs(arp->ea_hdr.ar_op);
/* Source/Target addresses from ARP packet */
uint32_t sender_ip, target_ip;
memcpy(&sender_ip, arp->arp_spa, 4);
memcpy(&target_ip, arp->arp_tpa, 4);
/* Record the sender in our cache */
arp_cache_insert(&g_arp_cache, sender_ip, arp->arp_sha);
if (op == ARPOP_REQUEST) {
/* Is this request for our IP? If so, reply. */
if (target_ip == my_ip) {
printf("Received ARP request from %s for our IP\n",
ether_ntoa((struct ether_addr *)arp->arp_sha));
send_arp_reply(sock_fd, ifname, my_ip, my_mac, sender_ip, arp->arp_sha);
}
} else if (op == ARPOP_REPLY) {
/* This is a reply; we've already cached above. */
char ipbuf[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &sender_ip, ipbuf, sizeof(ipbuf));
printf("Received ARP reply from %s (%s)\n",
ether_ntoa((struct ether_addr *)arp->arp_sha), ipbuf);
}
}
/* Example “send IPv4” function using ARP cache for resolution */
void send_ipv4_packet(int sock_fd, const char *ifname,
uint32_t my_ip, const uint8_t my_mac[ETH_ALEN],
uint32_t dst_ip, const uint8_t *payload, size_t payload_len) {
uint8_t dst_mac[ETH_ALEN];
if (!arp_cache_lookup(&g_arp_cache, dst_ip, dst_mac)) {
/* Not in cache -> broadcast ARP request and return.
* In a real stack you’d queue the IP packet and retry once ARP is resolved.
*/
printf("ARP cache miss for %s, sending ARP request\n", inet_ntoa(*(struct in_addr *)&dst_ip));
send_arp_request(sock_fd, ifname, my_ip, my_mac, dst_ip);
return;
}
/* Build an Ethernet + IP + payload frame here... */
/* This example just logs that we *would* send it. */
printf("Sending IP packet to %s via %s\n",
inet_ntoa(*(struct in_addr *)&dst_ip),
ether_ntoa((struct ether_addr *)dst_mac));
/* TODO: Build actual IP/TCP/UDP frame and send via PF_PACKET raw socket */
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <interface>\n", argv[0]);
return EXIT_FAILURE;
}
const char *ifname = argv[1];
uint8_t my_mac[ETH_ALEN];
uint32_t my_ip;
if (!get_interface_info(ifname, my_mac, &my_ip)) {
fprintf(stderr, "Could not get interface info for %s\n", ifname);
return EXIT_FAILURE;
}
printf("Interface %s: MAC %s, IP %s\n",
ifname,
ether_ntoa((struct ether_addr *)my_mac),
inet_ntoa(*(struct in_addr *)&my_ip));
/* Create raw socket for ARP */
int sock_fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
if (sock_fd < 0) {
perror("socket(AF_PACKET, SOCK_RAW, ETH_P_ARP)");
return EXIT_FAILURE;
}
/* Bind to the specific interface */
struct sockaddr_ll sll = {0};
sll.sll_family = AF_PACKET;
sll.sll_protocol = htons(ETH_P_ARP);
sll.sll_ifindex = if_nametoindex(ifname);
if (bind(sock_fd, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
perror("bind()");
close(sock_fd);
return EXIT_FAILURE;
}
arp_cache_init(&g_arp_cache);
/* Main loop: read ARP packets and process. You could use select() to
* integrate with other socket activity.
*/
while (1) {
uint8_t buf[1500];
ssize_t n = recv(sock_fd, buf, sizeof(buf), 0);
if (n < (ssize_t)(ETH_HLEN + sizeof(struct ether_arp))) {
if (n < 0) perror("recv()");
continue;
}
struct ether_header *eth = (struct ether_header *)buf;
if (ntohs(eth->ether_type) != ETH_P_ARP) {
continue; /* ignore non-ARP */
}
struct ether_arp *arp = (struct ether_arp *)(buf + ETH_HLEN);
handle_arp_packet(sock_fd, ifname, arp, my_ip, my_mac);
/* Example usage: Attempt to send an IP packet (payload omitted)
* In a real stack you’d have more complex logic here.
*/
// send_ipv4_packet(sock_fd, ifname, my_ip, my_mac, some_dst_ip, payload, payload_len);
}
close(sock_fd);
return 0;
}
How it works
- An
arp_cache holds up to ARP_CACHE_SIZE entries. Each entry tracks IP, MAC, when it was added and last used, and whether it’s valid.
arp_cache_insert() replaces existing or adds a new entry; if the cache is full, it evicts the least‑recently used entry (smallest last_used).
arp_cache_age() expires entries older than ARP_ENTRY_TTL.
- The main loop listens on a raw socket bound to the given interface for Ethernet frames of type
ETH_P_ARP. It parses incoming ARP requests/replies, populates the cache, and replies to ARP requests for the local IP.
send_arp_request() crafts a broadcast ARP request for the target IP; send_arp_reply() sends a reply to a requester.
send_ipv4_packet() shows how you would consult the cache to resolve a next‑hop’s MAC; in a real implementation you would also build and transmit an actual IP/TCP/UDP frame when a MAC is known, and queue the packet otherwise.
You will need to run this as root on Linux to open a raw socket. This code is simplified and meant as a starting point; a production TCP/IP stack has many more pieces (IP/TCP parsing, routing tables, retransmission, checksums, etc.), but the ARP cache with aging and LRU eviction is all here.