8000 GitHub - andersc/net-tools: Modern C++20 cross-platform networking toolkit with IPv4/IPv6 ping, traceroute, PMTU discovery, sockets, and network simulation. · GitHub
[go: up one dir, main page]

Skip to content
anderscPublic

About

Modern C++20 cross-platform networking toolkit with IPv4/IPv6 ping, traceroute, PMTU discovery, sockets, and network simulation.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

30 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🌐 net-tools

net-tools — Modern C++20 Networking

Build Linux Build Windows Build macOS License: MIT C++20

A modern C++20 cross-platform networking toolkit for diagnostics, testing, and development.


Features

  • 🚀 Modern C++20 — Templates, std::span, std::optional, std::chrono, if constexpr
  • 📦 Zero Dependencies — No external libraries required
  • 🖥️ Cross-Platform — Linux, macOS, and Windows support
  • 🔧 Easy Integration — Header + source files, just add to your project
  • 📊 Comprehensive — Full statistics, callbacks, and configurable options

Tools and Platform Support

Every tool builds on Linux, macOS, and Windows. The network-facing tools support both IPv4 and IPv6. NetSim operates on byte payloads and does not inspect or depend on the IP version.

Tool IPv4 IPv6 Permissions Documentation
NameResolver Yes Yes None Guide
NetworkInterfaces Yes Yes None Guide
TcpProbe Yes Yes None Guide
RouteInspector Yes Yes None Guide
NetworkIF Yes Yes None Guide
PmtuDiscoverer Yes Yes None Guide
Ping Yes Yes Linux: root or CAP_NET_RAW; macOS: root; Windows: none Guide
Traceroute (ICMP) Yes Yes Linux: root or CAP_NET_RAW; macOS: root; Windows: none Guide
Traceroute (UDP) Yes Yes Linux: root or CAP_NET_RAW; macOS: root; Windows: Administrator may be required Guide
NetSim N/A N/A None; IP-agnostic payload simulator Guide

Requirements

  • CMake 3.20 or later
  • C++20 compatible compiler:
    • GCC 10+
    • Clang 12+
    • MSVC 2022+ (Visual Studio 17)

Building

Linux / macOS

# Clone
git clone https://github.com/andersc/net-tools.git
cd net-tools

# Build
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build

# Test
ctest --test-dir build --output-on-failure

# Run the network simulator demo (no special privileges required)
./build/netsim_demo

Building, testing, and most of the toolkit do not require sudo. Ping and traceroute are the exceptions on Unix because their current backends use raw ICMP sockets. See Why Ping and Traceroute Need Extra Permission for the reason and the narrower Linux capability option.

EFP over UDP verification

When new-efp is checked out next to this project, CMake also builds efp_udp_e2e. Alternatively, set NET_TOOLS_EFP_INCLUDE_DIR to the directory containing efp.h. The server keeps one EFP receiver in each UDP client's std::any context, and the client can pass every outgoing EFP datagram through NetSim before transmission.

# Receiving host
./build/efp_udp_e2e --server --bind 0.0.0.0 --port 43300

# Sending host, with deterministic congested-4G loss and reordering
./build/efp_udp_e2e --client 192.0.2.10 --port 43300 --sim 4g --bundle quarter

Windows

# Clone
git clone https://github.com/andersc/net-tools.git
cd net-tools

# Build
cmake -B build -G "Visual Studio 17 2022" -A x64
cmake --build build --config Release

# Test
ctest --test-dir build --output-on-failure -C Release

# ICMP Ping and Traceroute use Windows IP Helper and need no elevation
.\build\Release\ping_demo.exe ::1 -6
.\build\Release\traceroute_demo.exe 127.0.0.1 --ipv4

Quick Examples

NameResolver — Names to Addresses and Back

#include "NameResolver.h"
#include <iostream>

auto lResult = NameResolver::resolve("example.com", 443);
if (!lResult.succeeded()) {
    std::cerr << nameResolverErrorToString(lResult.mError) << std::endl;
    return 1;
}

for (const auto& lEndpoint : lResult.mEndpoints) {
    std::cout << lEndpoint.toString() << std::endl;
}

auto lReverse = NameResolver::reverseLookup("2001:4860:4860::8888");
if (lReverse.succeeded()) std::cout << lReverse.mHostname << std::endl;

The resolver returns every unique address supplied by the operating system, supports IPv4, IPv6, and scoped IPv6 addresses, and uses the machine's normal DNS and hosts-file configuration.

The network_info_demo executable also provides resolve, reverse, interfaces, probe, and route commands without elevated privileges.

TcpProbe — Test a Service Without ICMP

#include "TcpProbe.h"

auto lProbe = TcpProbe::probe("example.com", 443);
if (lProbe.succeeded()) {
    std::cout << "Connected to " << lProbe.mRemoteEndpoint->toString()
              << " in " << (lProbe.mConnectTimeMicroseconds / 1000.0) << " ms"
              << std::endl;
}

RouteInspector — Show the Selected Local Path

#include "RouteInspector.h"

auto lRoute = RouteInspector::inspect("example.com");
if (lRoute.succeeded()) {
    std::cout << lRoute.mLocalEndpoint->mAddress.toString()
              << " via " << lRoute.mInterfaceName << std::endl;
}

Ping — Measure Latency

#include "Ping.h"
#include <iostream>

Ping lPing;
PingConfig lConfig;
lConfig.mCount = 4;

auto lResult = lPing.ping("google.com", lConfig);

std::cout << "Received: " << lResult.mStatistics.mPacketsReceived << "/" 
          << lResult.mStatistics.mPacketsSent << std::endl;
std::cout << "RTT avg: " << (lResult.mStatistics.mAvgRttMicroseconds / 1000.0)
          << " ms" << std::endl;
std::cout << "Packet loss: " << lResult.mStatistics.mPacketLossPercent << "%"
          << std::endl;

Traceroute — Discover Network Path

#include "Traceroute.h"
#include <iostream>

Traceroute lTraceroute;
TracerouteConfig lConfig;
lConfig.mMaxHops = 30;

auto lResult = lTraceroute.trace("google.com", lConfig);

for (const auto& lHop : lResult.mHops) {
    std::cout << lHop.mHopNumber << "  ";
    if (lHop.mResponded) {
        std::cout << lHop.mIpAddress << "  " 
                  << (lHop.mAvgRttMicroseconds / 1000.0) << " ms" << std::endl;
    } else {
        std::cout << "*" << std::endl;
    }
}

NetworkIF — UDP Echo Server

#include "NetworkIF.h"
#include <iostream>

UdpServer lServer;
lServer.create(IpVersion::DUAL);
lServer.bind(8080);

lServer.setOnDataReceived([&](const ClientInfo& aClient, std::span<const uint8_t> aData, std::any&) {
    std::cout << "Received " << aData.size() << " bytes from " << aClient.mIp << std::endl;
    int64_t lBytesSent = 0;
    lServer.sendTo(aData, aClient.mIp, aClient.mPort, lBytesSent);  // Echo back
});

while (true) {
    lServer.poll(100);
}

poll() uses non-blocking sockets and drains ready UDP packets, TCP data, and pending TCP connections in bounded batches (64 by default). This reduces poll overhead during bursts while preserving fairness between clients. Callbacks run synchronously, outside the global client-map lock, and may call removeClient() for the current client. See the NetworkIF Guide for tuning and native-handle rules.

PmtuDiscoverer — Find Path MTU

#include "PmtuDiscoverer.h"
#include <iostream>

Pmtu::UdpPmtuDiscoverer::Config lConfig;
lConfig.minPayload = 600;
lConfig.maxPayload = 1500;
lConfig.psk = "mysecretkey";

Pmtu::UdpPmtuDiscoverer lDiscoverer;
auto lResult = lDiscoverer.discover("192.168.1.1", 9000, lConfig);

std::cout << "Path MTU: " << lResult.inferredPathMtu << " bytes" << std::endl;

Project Structure

net-tools/
├── CMakeLists.txt          # Main build configuration
├── NetworkAddress.h/.cpp   # Portable IPv4/IPv6 address and endpoint types
├── NameResolver.h/.cpp     # Forward and reverse name resolution
├── NetworkInterfaces.h/.cpp # Local interface, address, MTU, and MAC discovery
├── TcpProbe.h/.cpp        # TCP reachability and connection timing
├── RouteInspector.h/.cpp  # Selected source address and local interface
├── NetworkIF.h/.cpp        # Network interface (UDP/TCP)
├── PmtuDiscoverer.h/.cpp   # Path MTU discovery
├── Traceroute.h/.cpp       # Unix traceroute implementation
├── TracerouteWindows.cpp   # Native Windows traceroute backend
├── Ping.h/.cpp             # Unix ping implementation
├── PingWindows.cpp         # Native Windows IP Helper backend
├── NetSim.h/.cpp           # WiFi/4G network simulator
├── *_main.cpp              # CLI demo applications
├── howto_*.md              # Documentation guides
└── tests/                  # Unit tests
    ├── CMakeLists.txt
    ├── NetworkUtilitiesTest.cpp
    ├── NetworkIFTest.cpp
    ├── PmtuDiscovererTest.cpp
    ├── TracerouteTest.cpp
    ├── PingTest.cpp
    └── NetSimTest.cpp

Running Tests

# Build and run all tests
cmake -B build -DCMAKE_BUILD_TYPE=Debug
cmake --build build
ctest --test-dir build --output-on-failure

# Run specific test
./build/tests/ping_tests config_defaults
./build/tests/traceroute_tests can_trace

The default test run needs no elevation. Raw-socket loopback tests report a skip when the process lacks permission. CI separately elevates and requires the IPv4 and IPv6 raw-socket Ping and Traceroute paths on Linux and macOS; the Windows workflow does the same for its Administrator-only UDP Traceroute path.


Permissions

NetworkIF, PMTU discovery, NetSim, and normal TCP/UDP applications run as an ordinary user on every supported platform. Extra permission applies only to backends that open raw ICMP sockets.

Why Ping and Traceroute Need Extra Permission

Ping sends and receives ICMP Echo packets. Traceroute controls the packet hop limit and listens for ICMP Time Exceeded and Destination Unreachable responses from routers. On Unix, net-tools implements these operations with raw ICMP sockets, which the operating system restricts because they allow an application to create and observe network-control packets.

This is not a requirement for the library as a whole. It applies only when using Ping or Traceroute on Linux/macOS, and when using UDP Traceroute on Windows. Windows Ping and ICMP Traceroute use the native IP Helper API and run without elevation.

Linux

# Grant only raw-network access to the two demo executables (recommended)
sudo setcap cap_net_raw+ep ./build/ping_demo
sudo setcap cap_net_raw+ep ./build/traceroute_demo

# The demos now run as your normal user
./build/ping_demo google.com
./build/traceroute_demo 8.8.8.8

CAP_NET_RAW is narrower than running the entire process as root. Reapply it after replacing or rebuilding an executable. Alternatively, prefix an individual command with sudo when you do not want to set a file capability.

macOS

# macOS has no Linux-style CAP_NET_RAW file capability
sudo ./build/ping_demo google.com
sudo ./build/traceroute_demo 8.8.8.8

Windows

Ping, ICMP traceroute, PMTU discovery, NetworkIF, and NetSim run as a normal user. UDP traceroute receives raw ICMP errors and may require an Administrator terminal; if access is denied, use the default --protocol icmp mode. The Windows GitHub Actions job explicitly requires and tests UDP traceroute over both IPv4 and IPv6, so this privileged path cannot silently be skipped in CI.


Documentation

Each tool has comprehensive documentation:


Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Follow the coding style
  4. Add tests for new functionality
  5. Submit a pull request

License

This project is licensed under the MIT License — see the LICENSE file for details.

About

Modern C++20 cross-platform networking toolkit with IPv4/IPv6 ping, traceroute, PMTU discovery, sockets, and network simulation.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages

0