How ccie18643/pytcp works
Project type and purpose
• PyTCP is a user-space implementation of the full TCP/IP stack written in Python. It exports a sockets-like API (TcpIpStack) so external applications or examples can send/receive Ethernet, ARP, IP4/6, ICMP4/6, UDP, and TCP traffic via a Linux TAP interface.
File structure
• Top-level “examples” directory holds sample clients/services that import and drive the stack.
• Core library under “pytcp”:
• lib/ – packet, socket, IP/MAC address utilities and the stack manager
• protocols/ – per-protocol handlers, each split into Fast Packet Parser (fpa), Packet Stats (ps), Pre-header receive (phrx), Pre-header transmit (phtx), and fast packet parser parse (fpp) modules for ARP, Ether, IPv4, IPv6 (+ ext headers), ICMP4/6, UDP, TCP, RAW
• subsystems/ – concurrent components (rx_ring, tx_ring, packet_handler, timer, arp_cache, nd_cache, tracker)
• Configuration, build (Makefile), CI, and docs.
Inspect README insights
• The stack runs as multiple threads/subsystems, attaches to a TAP interface, auto-configures IPv4 via DHCP and IPv6 via SLAAC/DAD, and implements routing, fragmentation, reassembly, sliding window TCP with congestion control, ARP/ND caches, and socket APIs.
Main components
a. External user / example script (e.g., run_stack.py, tcp_echo_client.py)
b. TcpIpStack library (pytcp/__init__.py)
c. Subsystems threads:
• RxRing: reads raw Ethernet frames from TAP
• PacketHandler: dispatches frames through protocol stack
• Protocol handlers (Ethernet → ARP/IPv4/IPv6 → ICMP4/6, UDP, TCP)
• ARP cache & ND cache: address resolution and DAD
• Timer: manages retransmit, DAD, and other time-based events
• TxRing: queues assembled frames to TAP
d. Utility libraries: packet, logger, ip4_address, ip6_address, mac_address, socket API
e. Linux TAP interface & host network stack / bridge
Relationships & data-flow
• Inbound flow: TAP → RxRing → PacketHandler → protocol chain (Ether → IP4/6 → transport) → socket or example
• Outbound flow: application/socket → session manager → protocol phtx modules → PacketHandler → TxRing → TAP
• Timer triggers retransmit or DAD events, interacts with PacketHandler and protocol handlers.
• ARP/ND cache responds to address resolution requests and informs PacketHandler.
Architectural patterns & tech
• Thread-per-subsystem concurrency model
• Zero-copy packet parsing/assembly (FPA/FPP modules)
• Modular protocol layering (each protocol in its own package)
• BSD-sockets-style API overlay
• TAP device integration for user-space networking