Lightweight Linux command-line network monitor that captures IPv4 packets and displays real-time TCP/UDP statistics.
Understanding network traffic patterns requires packet-level visibility. NetWatch provides a minimal, dependency-free tool that captures packets using Linux raw sockets and displays protocol distribution and top endpoints.
AF_PACKET raw socket (kernel) → PacketCapture (parse) → Statistics (aggregate) → stdout (display)
Single-threaded capture loop with a 1-second socket timeout for periodic display refresh.
Three classes:
PacketCapture— RAII raw socket wrapper; captures and parses Ethernet/IPv4/TCP/UDP headers with bounds checksStatistics— Accumulates packet/byte counts; tracks top endpoints viastd::unordered_mapPacket— Simple struct holding parsed packet information
- Raw packet capture via
AF_PACKET+SOCK_RAW(no libpcap) - IPv4/TCP/UDP header parsing with IHL-aware bounds checking
- Real-time protocol distribution (packet counts, byte counts, percentages)
- Top-5 endpoint tracking
- RAII resource management for socket cleanup
- Graceful Ctrl+C termination via
std::atomicsignal flag
- C++17 —
std::optional,std::atomic, structured bindings - Linux APIs —
AF_PACKET,SOCK_RAW,ETH_P_IP,SO_RCVTIMEO - STL —
std::unordered_map,std::vector,std::partial_sort - CMake — build system
cd NetWatch
mkdir build && cd build
cmake ..
makeRequires CAP_NET_RAW capability or root:
# Option 1: run as root
sudo ./netwatch
# Option 2: set capability (preferred, one-time)
sudo setcap cap_net_raw+ep ./netwatch
./netwatch=== NetWatch ===
Packets captured : 1284
TCP packets : 934
UDP packets : 350
Total bytes : 2.41 MB
TCP : 72.74%
UDP : 27.26%
--- Top Endpoints ---
192.168.1.10:52341 -> 142.250.190.46:443 (312 pkts)
192.168.1.10:52342 -> 142.250.190.46:443 (287 pkts)
192.168.1.10:43210 -> 8.8.8.8:53 (89 pkts)
Press Ctrl+C to stop.
- Linux raw socket programming (
AF_PACKET,SOCK_RAW) - Network protocol stack (Ethernet → IPv4 → TCP/UDP)
- Packet header parsing with bounds checking and IHL field handling
- RAII for system resource management
- Signal-safe graceful shutdown (
std::atomic) - STL containers for real-time data aggregation
constcorrectness and encapsulation
- Per-interface filtering via
bind()+sockaddr_ll - IPv6 support
- Configurable display refresh interval
- Packet rate (packets/sec) tracking
- BPF filtering for targeted capture