Chapter 4: Ad-Hoc and Peer-to-Peer Networks

Networks Without Permission

Every network we have discussed so far — LANs, mesh networks, point-to-point links — shares a common assumption: someone, somewhere, set up infrastructure before communication could begin. Someone installed a router, configured an access point, ran cables through walls. There is a plan, a topology, a design.

But what happens when there is no plan? When two devices need to talk right now, in a field, in a disaster zone, in a protest, in a village with no infrastructure at all? What happens when you want to share a file with someone across the world without any server in the middle? What happens when the very concept of a central authority is the problem you are trying to solve?

This is the domain of ad-hoc networks and peer-to-peer (P2P) architectures — two deeply related ideas that together represent the most radically decentralized approach to networking. Ad-hoc networks eliminate the need for infrastructure. Peer-to-peer architectures eliminate the need for servers. Combined, they produce communication systems that can spring into existence spontaneously, operate without anyone’s permission, and resist every form of centralized control.

If mesh networking (Chapter 3) is about building resilient infrastructure, ad-hoc and P2P networking is about building networks that need no infrastructure at all.

This chapter covers the theory, the protocols, and the practical tools for creating networks that exist only because the participants chose to create them — networks that live and die with the devices that form them, that carry data through chains of strangers, that store files in swarms of cooperating peers. These are the networks that work when everything else has failed, and the architectures that keep the internet’s original promise of decentralization alive in an era of increasing consolidation.

Understanding Ad-Hoc Networks

What Makes a Network “Ad-Hoc”?

The term ad-hoc comes from Latin, meaning “for this” — created for a particular, immediate purpose, without prior planning. An ad-hoc network is a network that forms spontaneously between devices without relying on pre-existing infrastructure like routers, access points, or cell towers.

In standard Wi-Fi networking — what the IEEE calls infrastructure mode — every device connects to a central access point (AP). Want to send a message from your laptop to your phone? The laptop sends it to the AP, and the AP forwards it to your phone, even if your phone is sitting right next to your laptop. The access point is the intermediary, the authority, the single point of failure. Remove it, and communication stops.

In ad-hoc mode — formally known as Independent Basic Service Set (IBSS) in the 802.11 specification — devices communicate directly with each other. There is no access point. No hierarchy. No central authority. Each device is simultaneously a sender and a receiver, and the network exists only as long as the participating devices choose to maintain it.

The distinction is fundamental. Infrastructure mode is a star topology with a privileged center. Ad-hoc mode is a graph of equals. This simple architectural difference has profound implications for resilience, privacy, censorship resistance, and the ability to create networks in environments where no infrastructure exists.

Characteristics of Ad-Hoc Networks

Ad-hoc networks share several defining characteristics:

No pre-existing infrastructure required. The network forms from the devices themselves. No one needs to install an access point, configure a DHCP server, or run cables. If two devices with compatible radios are within range of each other, a network can exist.

Dynamic topology. Nodes can join, leave, or move at any time. The network’s shape is constantly changing. A device that was reachable a moment ago may have walked out of range, run out of battery, or simply been turned off. The network must adapt continuously.

Distributed control. There is no single device that manages the network. Addressing, routing, and medium access are handled cooperatively by all participants. This eliminates single points of failure but introduces coordination challenges.

Resource constraints. Ad-hoc networks are often formed by battery-powered mobile devices — phones, laptops, sensors — that have limited energy, processing power, and bandwidth. Protocols designed for ad-hoc networks must be efficient with these scarce resources.

Security challenges. Without a central authority to manage authentication and access control, ad-hoc networks face unique security challenges. Any device within radio range can attempt to join, eavesdrop, or disrupt the network. Trust must be established through cryptographic means rather than physical infrastructure.

MANETs: Mobile Ad-Hoc Networks

The academic and military communities formalized the study of ad-hoc networking under the name MANETMobile Ad-hoc Network. A MANET is an ad-hoc network in which nodes are mobile, meaning the topology changes not just because devices join or leave, but because they physically move through space.

MANETs were originally researched for military applications. Soldiers moving through terrain need to communicate without deploying fixed infrastructure that could be targeted. Each soldier’s radio serves as both an endpoint and a router, forwarding messages for others. If one soldier moves out of range, the network automatically reroutes through other nearby soldiers.

The challenges of MANETs are formidable. Routing protocols must handle constant topology changes without consuming excessive bandwidth for route updates. The AODV (Ad-hoc On-demand Distance Vector) protocol, for example, does not maintain routes continuously — it discovers routes only when a node actually needs to send data, reducing overhead when the network is idle but introducing latency when new routes must be found. DSR (Dynamic Source Routing) takes a different approach, having the source node include the entire route in each packet’s header, which avoids the need for intermediate nodes to maintain routing tables but adds overhead to every packet.

For alternative networks, MANET principles are directly relevant. A group of people at a protest, a music festival, or a disaster relief operation can form a MANET with their phones — if the right software is installed — and communicate without any cellular or internet infrastructure.

VANETs: Vehicular Ad-Hoc Networks

VANETsVehicular Ad-hoc Networks — are a specialized form of MANET where the mobile nodes are vehicles. Cars, trucks, buses, and emergency vehicles equipped with wireless transceivers can form networks that share traffic information, hazard warnings, and other data.

VANETs have unique characteristics that distinguish them from general MANETs. Vehicles move at high speeds, so nodes enter and leave communication range rapidly. But vehicles also move in constrained, predictable patterns — they follow roads — which can actually simplify routing compared to the unconstrained movement of pedestrians. The DSRC (Dedicated Short-Range Communications) standard, operating in the 5.9 GHz band, was developed specifically for vehicle-to-vehicle (V2V) and vehicle-to-infrastructure (V2I) communication.

While VANETs might seem outside the scope of alternative networking, the underlying technology is deeply relevant. Imagine a rural area where vehicles traveling along a road form temporary networks, carrying data between isolated communities. A message could be given to a truck driver heading to town, stored in the truck’s onboard computer, and delivered when the truck reaches a location with internet connectivity. This is not science fiction — it is a form of delay-tolerant networking, which we will explore later in this chapter.

Peer-to-Peer Architecture

The Philosophy of Equals

The conventional internet is overwhelmingly built on the client-server model. Your web browser (client) sends a request to Google’s server. Your email client talks to your provider’s mail server. Your streaming app fetches video from Netflix’s content delivery network. In every interaction, there is a clear asymmetry: the client asks, the server provides.

Peer-to-peer (P2P) architecture rejects this asymmetry. In a P2P system, every participant — every peer — is both client and server simultaneously. Peers request resources from other peers and provide resources to other peers. There is no distinguished server, no central authority, and no single point of failure.

The distinction between ad-hoc networks and P2P networks is worth clarifying. Ad-hoc networks are a physical-layer and network-layer concept — they describe how devices connect wirelessly without infrastructure. P2P is an application-layer and architectural concept — it describes how software systems organize without central servers. You can run P2P software over a conventional internet connection, and you can run client-server software over an ad-hoc network. But the combination of ad-hoc networking with P2P architecture produces the most radically decentralized systems possible: networks with no infrastructure and no servers.

Pure P2P vs. Hybrid P2P

Not all P2P systems are created equal. The spectrum ranges from pure P2P — where every peer is truly equal and no central component exists — to hybrid P2P — where some centralized elements assist with coordination while the actual data transfer happens peer-to-peer.

Pure P2P systems have no central point of failure whatsoever. The original Gnutella network (used by early file-sharing applications) was pure P2P: peers discovered each other through flooding queries across the network, with no central directory. The drawback was inefficiency — finding a file could require querying thousands of peers — but the architecture was virtually indestructible. No company, government, or lawsuit could shut it down because there was nothing central to shut down.

Hybrid P2P systems use central components for specific functions — usually peer discovery or search indexing — while keeping data transfer decentralized. The original Napster was hybrid P2P: it maintained a central server that indexed which files each peer had, but the actual file transfers happened directly between peers. This was more efficient than pure P2P but created a single point of failure — when Napster’s central servers were shut down by court order, the entire system collapsed.

Modern P2P systems have found clever middle grounds. BitTorrent uses trackers (central servers that help peers find each other for specific files) but also supports DHT-based peer discovery that works without any tracker. The result is a system that benefits from centralized efficiency when trackers are available but degrades gracefully to fully decentralized operation when they are not.

Distributed Hash Tables (DHTs)

The key innovation that made efficient pure P2P possible was the Distributed Hash Table (DHT) — a data structure that distributes the storage and lookup of key-value pairs across a network of peers, with no central server.

Imagine you have a million files shared across ten thousand peers. How do you find which peer has the file you want without asking all ten thousand? A central index server would be the obvious answer, but that creates a single point of failure. A DHT solves this problem by assigning every peer and every piece of content a position in a shared address space (typically a large number, like a 160-bit integer). Each peer is responsible for storing information about content whose address is close to its own address. When you want to find content, you compute its address and then route your query through the network toward the peer responsible for that region of the address space.

Kademlia is the DHT algorithm used by BitTorrent, IPFS, and Ethereum’s peer discovery. It uses an XOR distance metric — the “distance” between two addresses is computed by XORing them together — which has elegant mathematical properties. Each node maintains a routing table of other nodes, organized into k-buckets based on their XOR distance. Looking up a key requires contacting $O(\log n)$ nodes in a network of $n$ peers, making lookups efficient even in very large networks.

import hashlib

def compute_node_id(address):
    """Compute a 160-bit node ID from an address string."""
    return int(hashlib.sha1(address.encode()).hexdigest(), 16)

def xor_distance(id1, id2):
    """Compute XOR distance between two node IDs."""
    return id1 ^ id2

node_a = compute_node_id("192.168.1.10:8000")
node_b = compute_node_id("192.168.1.11:8000")
print(f"Distance: {xor_distance(node_a, node_b)}")

Chord is another well-known DHT algorithm that organizes nodes on a circular identifier space. Each node maintains a finger table — a routing table where the $i$-th entry points to the node responsible for the position $(\text{current} + 2^i) \mod 2^m$ in the ring. This structure guarantees $O(\log n)$ lookup time and handles node joins and departures gracefully.

For alternative networks, DHTs are foundational technology. They allow a network of peers to collectively maintain a directory of available resources — files, services, contact information — without any central server. When a peer goes offline, the DHT redistributes its responsibilities to neighboring peers. When new peers join, they gradually take over responsibility for their portion of the address space.

NAT Traversal and Hole Punching

One of the most persistent practical obstacles to P2P networking is Network Address Translation (NAT). Most devices on the internet sit behind a NAT router — your home router, for example, has one public IP address and gives private addresses (like 192.168.x.x) to your internal devices. Outgoing connections work fine, but incoming connections are blocked by default because the NAT router does not know which internal device should receive them.

This is a fundamental problem for P2P systems. If both peers are behind NAT, neither can directly connect to the other. Several techniques exist to work around this:

STUN (Session Traversal Utilities for NAT) allows a peer to discover its public IP address and the type of NAT it is behind by communicating with a STUN server on the public internet. This information is then shared with the other peer, which can attempt a direct connection.

TURN (Traversal Using Relays around NAT) is the fallback when direct connection is impossible. A TURN server on the public internet relays traffic between the two peers. This works through any NAT but requires a server and adds latency.

Hole punching is the clever technique that makes direct peer-to-peer connections possible through most NATs. Both peers simultaneously send packets to each other’s public addresses (learned via STUN). These outgoing packets create temporary entries in their respective NAT tables. When the incoming packet from the other peer arrives, the NAT recognizes it as a response to the outgoing packet and allows it through. It is like two people simultaneously opening their front doors to let each other in.

import socket
import threading

def udp_hole_punch(local_port, remote_ip, remote_port):
    """Basic UDP hole punching demonstration."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(('0.0.0.0', local_port))
    # Send a packet to create NAT mapping
    sock.sendto(b'punch', (remote_ip, remote_port))
    # Now listen for incoming packets through the hole
    sock.settimeout(10)
    try:
        data, addr = sock.recvfrom(1024)
        print(f"Received '{data.decode()}' from {addr}")
    except socket.timeout:
        print("No response — NAT type may not support punching")

For alternative networks operating entirely on a local mesh or LAN, NAT traversal is often unnecessary — all devices are on the same network with direct reachability. But the moment you want to connect your local alternative network to peers on the broader internet, NAT traversal becomes essential.

Gossip Protocols

Gossip protocols (also called epidemic protocols) are a family of communication algorithms inspired by how rumors spread in human social networks. Each node periodically selects a random peer and exchanges information with it. Over time, information spreads exponentially through the network — like a virus or a rumor — until every node has received it.

The beauty of gossip protocols lies in their simplicity and robustness. They require no central coordination, handle node failures gracefully (if one node goes down, information still spreads through other paths), and scale naturally. The mathematical properties are well-understood: in a network of $n$ nodes, information reaches all nodes in $O(\log n)$ rounds of gossip with high probability.

Gossip protocols are used in many real-world systems:

For alternative networks, gossip protocols are particularly attractive because they work well in unreliable environments. If a node is temporarily unreachable, it will catch up the next time a peer gossips with it. If the network partitions, information continues spreading within each partition and reconciles when the partition heals.

import random

def gossip_round(nodes, informed, fanout=3):
    """Simulate one round of gossip protocol."""
    newly_informed = set()
    for node in list(informed):
        # Each informed node tells 'fanout' random peers
        targets = random.sample(
            [n for n in nodes if n != node], 
            min(fanout, len(nodes) - 1)
        )
        for target in targets:
            newly_informed.add(target)
    informed.update(newly_informed)
    return informed

Creating Ad-Hoc Networks on Linux

Using iw and wpa_supplicant for IBSS Mode

Linux provides excellent support for ad-hoc (IBSS) networking through the iw command-line tool and wpa_supplicant. Setting up an ad-hoc network on Linux requires bringing down any existing wireless connection, switching the interface to IBSS mode, and joining or creating a cell.

Here is the process step by step. First, identify your wireless interface and ensure it is not being managed by NetworkManager or another network manager that will interfere:

# Stop NetworkManager from managing the interface
sudo nmcli device set wlan0 managed no

# Bring down the interface
sudo ip link set wlan0 down

# Set the interface type to IBSS (ad-hoc)
sudo iw wlan0 set type ibss

# Bring the interface back up
sudo ip link set wlan0 up

# Join or create an IBSS cell
sudo iw wlan0 ibss join MyAdHocNet 2412

The number 2412 is the frequency in MHz — this corresponds to Wi-Fi channel 1 in the 2.4 GHz band. Common channel-to-frequency mappings you will use:

Channel Frequency (MHz)
1 2412
6 2437
11 2462

Channel selection matters. Choose a channel with minimal interference from nearby Wi-Fi networks. In most environments, channels 1, 6, and 11 are the standard non-overlapping channels in the 2.4 GHz band.

If you want to add WPA encryption to your IBSS network (and you should — unencrypted ad-hoc networks are trivially eavesdropped), you will need wpa_supplicant:

# Create a wpa_supplicant configuration for IBSS
cat > /tmp/ibss.conf << EOF
network={
    ssid="MyAdHocNet"
    mode=1
    frequency=2412
    key_mgmt=WPA-NONE
    pairwise=NONE
    group=TKIP
    psk="my_secret_passphrase"
}
EOF

sudo wpa_supplicant -i wlan0 -c /tmp/ibss.conf -D nl80211

Wi-Fi Direct with wpa_supplicant

Wi-Fi Direct (also known as Wi-Fi P2P) is a newer standard that allows devices to connect directly without an access point, similar to IBSS but with some important improvements. Wi-Fi Direct supports WPA2 encryption natively, has better device discovery, and is supported on most modern smartphones and laptops.

On Linux, Wi-Fi Direct is configured through wpa_supplicant’s P2P functionality:

# Start wpa_supplicant with P2P support
sudo wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf -D nl80211

# Use wpa_cli to discover peers
wpa_cli -i wlan0 p2p_find

# Connect to a discovered peer
wpa_cli -i wlan0 p2p_connect <peer_mac> pbc

Wi-Fi Direct creates a P2P Group where one device acts as the Group Owner (GO) — functionally similar to a soft access point — and others connect as clients. This is slightly less egalitarian than pure IBSS, but it provides better compatibility with devices that do not support IBSS mode (including most Android phones in recent versions, which have dropped IBSS support in favor of Wi-Fi Direct).

Configuring IP Addressing Without DHCP

In an ad-hoc network, there is no DHCP server to hand out IP addresses. You have several options:

Static addressing is the simplest approach. Each device manually configures an IP address from a shared subnet:

# On device 1
sudo ip addr add 10.0.0.1/24 dev wlan0

# On device 2
sudo ip addr add 10.0.0.2/24 dev wlan0

This works for small networks where participants can coordinate, but it does not scale. If two devices accidentally choose the same address, you get a conflict that is difficult to diagnose.

IPv6 link-local addressing solves this problem automatically. Every network interface automatically generates a link-local IPv6 address (in the fe80::/10 range) derived from its MAC address. These addresses are guaranteed unique on the local link and require zero configuration:

# Check your link-local IPv6 address
ip -6 addr show dev wlan0 scope link

The downside is that link-local addresses are only valid on the local network segment and cannot be routed. For a simple ad-hoc network where all devices are within range of each other, this is fine. For multi-hop ad-hoc networks, you need routable addresses.

IPv4 Link-Local (APIPA) is the IPv4 equivalent. Devices automatically assign themselves an address in the 169.254.0.0/16 range using the algorithm defined in RFC 3927. On Linux, avahi-autoipd implements this:

sudo avahi-autoipd wlan0

Auto-Discovery with mDNS

Once devices have IP addresses, they need to find each other. In conventional networks, DNS servers provide name resolution. In ad-hoc networks, mDNS (Multicast DNS) — implemented on Linux by Avahi — allows devices to discover each other by name without any server:

# Install and start Avahi
sudo apt install avahi-daemon
sudo systemctl start avahi-daemon

# Now other devices can reach you at <hostname>.local
ping my-laptop.local

Avahi also supports service discovery — devices can advertise services (web servers, file shares, chat services) that other devices can discover automatically. This is extremely useful for ad-hoc networks where you do not know in advance what services are available.

Bluetooth and BLE Networking

Bluetooth PAN (Personal Area Network)

While Wi-Fi gets most of the attention in alternative networking discussions, Bluetooth has quietly become one of the most ubiquitous wireless technologies on the planet. Every smartphone, every laptop, most tablets, and an ever-growing number of embedded devices have Bluetooth radios. This near-universal availability makes Bluetooth an important tool for ad-hoc communication, even with its significant limitations.

Bluetooth PAN (Personal Area Network) allows Bluetooth devices to form an IP network. One device acts as the Network Access Point (NAP) or Group Ad-hoc Network (GN), and other devices connect as PAN Users (PANU). Once connected, standard IP traffic flows over the Bluetooth link.

On Linux, setting up a Bluetooth PAN uses the bluez stack:

# Make device discoverable
sudo hciconfig hci0 piscan

# Create a PAN network bridge
sudo brctl addbr pan0
sudo ip addr add 10.10.0.1/24 dev pan0
sudo ip link set pan0 up

The range and throughput limitations of Bluetooth are significant. Classic Bluetooth (up to version 3.0) has a theoretical maximum throughput of about 3 Mbps and a range of approximately 10 meters for Class 2 devices (the most common power class in consumer devices) or up to 100 meters for Class 1 devices. Bluetooth 5.0 extended the range significantly — up to 200 meters line-of-sight for low-data-rate modes — and increased throughput to about 2 Mbps.

These numbers make Bluetooth unsuitable for streaming video or transferring large files. But for text messaging, sensor data, small file transfers, and emergency communication, Bluetooth’s combination of universal availability, low power consumption, and no need for any infrastructure makes it invaluable.

BLE Mesh Networking

Bluetooth Low Energy (BLE), introduced in Bluetooth 4.0, was designed specifically for low-power applications — fitness trackers, smart home sensors, beacons. Bluetooth Mesh, ratified in 2017, extends BLE to support mesh networking with up to 32,767 nodes.

Bluetooth Mesh uses a managed flooding approach — messages are broadcast and rebroadcast by relay nodes until they reach their destination. This is simpler than the routing-table-based approaches used by Wi-Fi mesh protocols, but it limits scalability. To prevent broadcast storms, Bluetooth Mesh uses a TTL (Time to Live) field, a message cache (so nodes do not rebroadcast messages they have already seen), and relay node designation (not all nodes need to relay messages).

The primary use case for Bluetooth Mesh today is smart building automation — controlling lights, HVAC systems, and sensors across a building. But its potential for alternative networking is significant. Imagine a neighborhood where every smartphone acts as a Bluetooth Mesh relay node, creating a communication network that requires no Wi-Fi, no cell towers, and no internet connection.

Bluetooth-Based Messaging Applications

Several applications leverage Bluetooth (and Wi-Fi Direct) for infrastructure-free messaging:

Briar is an open-source messenger designed for activists, journalists, and anyone who needs secure, censorship-resistant communication. Briar can communicate over Bluetooth, Wi-Fi Direct, and Tor. When internet connectivity is available, messages route through the Tor network. When it is not, Briar falls back to direct Bluetooth or Wi-Fi connections between nearby devices. Messages are stored locally on each device — there is no central server at all. Briar implements the Bramble Transport Protocol, which provides forward secrecy and works across all three transport layers.

Bridgefy gained attention during the 2019 Hong Kong protests, where protesters used it to communicate after the government disrupted cellular networks. Bridgefy uses Bluetooth to create a mesh network between nearby phones, with messages hopping from device to device to reach their destination. However, security researchers later found significant vulnerabilities in Bridgefy’s protocol, highlighting the importance of using well-audited cryptographic implementations.

Range, Throughput, and Power Considerations

Choosing between Bluetooth, Wi-Fi, and other wireless technologies for ad-hoc networking involves navigating a three-way tradeoff:

Technology Range (typical) Throughput Power Draw
Bluetooth 5 LE 50–200 m 125 kbps–2 Mbps Very low
Wi-Fi Direct 50–200 m 50–250 Mbps High
Wi-Fi IBSS 50–100 m 10–100 Mbps High
LoRa (Ch. 5) 2–15 km 0.3–27 kbps Extremely low

For battery-powered devices — which is most of what you will use in an ad-hoc network — power consumption is often the deciding constraint. A Bluetooth LE radio can run for months or years on a coin cell battery. A Wi-Fi radio in active mode drains a phone battery in hours. This tradeoff between capability and endurance is one of the central design tensions in alternative networking.

Delay-Tolerant Networking (DTN)

When “Always Connected” Is a Fantasy

Every networking protocol we use daily — TCP, HTTP, SMTP — assumes that a continuous, reasonably fast path exists between source and destination. TCP literally requires a handshake before data transfer begins: “Hello, are you there? Great, let me send you some data. Did you get it? Good.” If the connection drops mid-conversation, TCP gives up and reports an error.

Delay-Tolerant Networking (DTN) — also known as disruption-tolerant networking — is an architectural approach designed for environments where this assumption of continuous connectivity is false. In DTN, connections between nodes may be intermittent, latency may be measured in hours or days rather than milliseconds, and there may never be a complete end-to-end path between source and destination at any single moment in time.

The Bundle Protocol

The core of DTN is the Bundle Protocol, defined in RFC 5050 and its successor RFC 9171. Instead of establishing connections and sending streams of packets, the Bundle Protocol packages data into discrete units called bundles — self-contained messages that include the payload, source and destination addresses, and metadata about how the bundle should be handled (priority, lifetime, custody requirements).

Bundles are designed to be persistent. Unlike IP packets, which are discarded if they cannot be forwarded immediately, bundles are stored by intermediate nodes until a forwarding opportunity arises. This is the fundamental paradigm shift: from store-and-forward (receive a packet, immediately forward it) to store-carry-forward (receive a bundle, carry it potentially for a long time, and forward it when possible).

Store-Carry-Forward

The store-carry-forward paradigm is what makes DTN uniquely suited to alternative networking in challenging environments. Here is how it works in practice:

Imagine a remote village connected to the nearest town by a bus that runs once daily. A DTN node in the village stores messages from villagers. When the bus arrives, a DTN node on the bus receives these messages. The bus physically carries the messages along its route. When the bus reaches the town, its DTN node delivers the messages to the town’s DTN node, which forwards them to their final destinations — perhaps over the internet, perhaps to another bus heading to another village.

This is not hypothetical. The DakNet project in India deployed exactly this system, using buses and motorcycles equipped with Wi-Fi to carry data between rural kiosks and internet-connected base stations. Users could send and receive email, access government services, and participate in e-commerce — with latency measured in hours rather than milliseconds, but with zero ongoing infrastructure cost.

DTN in Space

NASA’s most ambitious use of DTN is in deep space communication. When communicating with spacecraft on Mars, the round-trip signal delay is between 6 and 44 minutes depending on orbital positions. The sun periodically blocks communication entirely. Equipment failures can interrupt contact for days. Traditional TCP/IP simply cannot function in this environment.

NASA has deployed the Interplanetary Overlay Network (ION) — a DTN implementation — on the International Space Station and various spacecraft. Bundles are routed through a network of relay satellites and ground stations, with each node storing bundles until a communication window opens. The protocol handles the multi-minute delays, the intermittent connectivity, and the asymmetric link capacity (downlink from spacecraft is typically much faster than uplink) that characterize space networking.

The irony is delicious: the technology NASA uses to communicate across interplanetary distances is the same technology that can connect a village without internet to the wider world.

DTN for Rural and Developing Areas

Beyond the DakNet example, DTN has been deployed and researched in numerous developing-world scenarios:

KioskNet used buses and taxis in rural India to carry data bundles between villages and internet-connected town centers. Each vehicle was equipped with a small computer and a Wi-Fi radio that automatically exchanged data with roadside kiosks as the vehicle passed.

First Mile Solutions deployed a similar system in Cambodia, using motorcycles as data mules to connect rural health clinics.

Serval Mesh incorporated DTN principles into a smartphone mesh networking application designed for disaster response and communication in areas without infrastructure.

The common thread is that DTN transforms the intermittent, unreliable connectivity typical of developing and rural areas from a problem into a design parameter. Instead of waiting for “real” internet infrastructure that may never come, DTN says: work with what you have. If that is a bus that comes once a day, build a network around the bus.

File Sharing and Content Distribution

BitTorrent: The Protocol That Changed Everything

BitTorrent, created by Bram Cohen in 2001, is the most successful P2P protocol ever deployed. At its peak, BitTorrent traffic accounted for over a third of all internet traffic. Its success came from a single brilliant insight: instead of downloading a file from one server, break the file into pieces and download different pieces from many peers simultaneously.

The key concepts of BitTorrent:

A torrent file (or a magnet link) contains metadata about the file being shared: its name, size, the SHA-1 hashes of each piece, and the addresses of one or more trackers. A tracker is a server that coordinates peers sharing a particular file — it does not host the file itself, only keeps track of who has which pieces.

When you start downloading, your BitTorrent client contacts the tracker and receives a list of peers who have (or are downloading) the file. You connect to these peers and begin exchanging pieces. The protocol uses a tit-for-tat strategy: you preferentially upload to peers who are uploading to you, which incentivizes sharing rather than freeloading.

A seeder is a peer that has the complete file and is only uploading. A leecher is a peer that is still downloading. A healthy torrent has a good ratio of seeders to leechers. The health of the swarm is self-regulating: as more people download the file, there are more peers to download from, so popular files actually become faster to download — the exact opposite of the client-server model, where popularity strains the server.

BitTorrent’s use of DHT for trackerless operation makes it particularly relevant for alternative networks. With DHT enabled, peers can find each other without any central tracker, making the system fully decentralized. The PEX (Peer Exchange) protocol further enhances decentralization by having peers share their peer lists with each other.

IPFS: The InterPlanetary File System

IPFS (InterPlanetary File System), created by Juan Benet and Protocol Labs, is an ambitious project to create a decentralized, content-addressed, peer-to-peer file system. Where BitTorrent distributes specific files, IPFS aims to create a new protocol for the web itself.

The key innovation of IPFS is content addressing. Instead of identifying files by their location (like a URL: “this file is on this server at this path”), IPFS identifies files by their content: each file’s address is a cryptographic hash of its contents. If two people add the same file to IPFS, it gets the same address. If a file is modified, it gets a new address. This means content on IPFS is immutable and verifiable — you can always check that the file you received is the exact file you requested by recomputing its hash.

IPFS uses a Kademlia-based DHT for peer discovery and content routing, Bitswap (a BitTorrent-inspired protocol) for data exchange, and Merkle DAGs (directed acyclic graphs where each node’s identifier is the hash of its contents) for organizing data.

For alternative networks, IPFS offers a compelling vision: a community’s shared knowledge — documents, manuals, educational materials, local news — could be stored on IPFS and replicated across multiple nodes in the community. Even if individual nodes go offline, the content remains available as long as at least one node has it pinned. And because content is addressed by hash rather than by server location, it works perfectly in environments where IP addresses change frequently — exactly the situation in ad-hoc and mesh networks.

Dat / Hypercore Protocol

Hypercore (originally called Dat) is a peer-to-peer data distribution protocol designed by the Dat Project (now the Hypercore Protocol team). Like IPFS, it uses content addressing and distributes data across multiple peers. Unlike IPFS, Hypercore is designed specifically for mutable datasets — datasets that change over time, like a website, a scientific dataset, or a shared document folder.

Hypercore uses an append-only log structure: data is added to the log over time, and each entry is cryptographically linked to the previous one (similar to a blockchain, but much simpler). Peers can selectively sync portions of the log, and the protocol efficiently handles updates — when a dataset changes, peers only need to download the new entries, not the entire dataset.

Hyperdrive builds on Hypercore to provide a distributed file system, and Hyperswarm handles peer discovery and NAT traversal. The ecosystem is designed to be practical: you can use it to host a website that is replicated across peers, share a folder that stays synchronized, or publish a dataset that others can follow and verify.

Sneakernet: The Ultimate Delay-Tolerant Network

The most underrated data distribution system in the world requires no radio waves, no cables, and no protocols more complex than “hand this to someone.” The sneakernet — physically carrying storage media from one location to another — is the original and, in many ways, still the most effective delay-tolerant network.

The numbers are compelling. A 1 TB USB drive costs about $20 and fits in your pocket. Driving it from New York to Los Angeles takes about 40 hours. That is an effective bandwidth of roughly 55 Gbps — faster than virtually any internet connection available to consumers. AWS recognized this reality with their Snowball service: a ruggedized storage appliance that they literally ship to your location, you fill with data, and ship back. For petabyte-scale data transfers, FedEx is still faster than the internet.

For alternative networks, the sneakernet is not a joke — it is a legitimate and often optimal strategy. A community without internet connectivity can exchange large datasets — educational materials, software updates, media libraries — by periodically exchanging hard drives. Combined with DTN principles, this becomes a structured data distribution system: designated carriers follow regular routes, exchanging data at each stop, like a digital postal service.

“Never underestimate the bandwidth of a station wagon full of tapes hurtling down the highway.” — Andrew S. Tanenbaum

P2P Communication Applications

Briar: Tor-Based P2P Messaging

Briar deserves special attention because it is perhaps the most thoughtfully designed P2P communication tool for the exact scenarios this book addresses. Developed by the Briar Project, it is designed to be usable by journalists, activists, and anyone who needs communication that is resistant to surveillance and censorship.

Briar’s architecture is unique. It can operate over three transport layers:

  1. The Tor network — when internet connectivity is available, messages are routed through Tor, providing anonymity and censorship resistance.
  2. Wi-Fi — when devices are on the same local network, messages are exchanged directly over Wi-Fi, never touching the internet.
  3. Bluetooth — when neither internet nor Wi-Fi is available, Briar falls back to direct Bluetooth connections between nearby devices.

Messages are stored exclusively on the devices of the participants — there is no server, no cloud backup, no metadata trail. Briar implements perfect forward secrecy, meaning that even if a device is later compromised, past messages cannot be decrypted.

The key limitation is that Briar only works on Android (though a desktop version is in development). And because there is no server to store messages, both parties must be online simultaneously for messages to be delivered — unless they are within Bluetooth or Wi-Fi range, in which case messages can be delivered when proximity allows.

Tox: Distributed Instant Messaging

Tox is a peer-to-peer, end-to-end encrypted instant messaging and video calling protocol. Unlike Briar, Tox operates over the internet but without any central servers. Peer discovery uses a DHT, and all communication is encrypted using NaCl (Networking and Cryptography library) cryptography.

Tox supports text messaging, voice calls, video calls, file transfer, and group chats — all peer-to-peer, all encrypted. Multiple client implementations exist, including qTox (desktop) and aTox (Android).

The main challenge with Tox is NAT traversal. Because there are no servers to relay traffic, peers behind restrictive NATs may be unable to connect. Tox addresses this partially through its DHT-based relay system, but connectivity can be unreliable in complex network environments.

RetroShare: Encrypted P2P Platform

RetroShare is a comprehensive P2P communication platform that provides encrypted messaging, file sharing, forums, channels, voice and video calls, and even a distributed email system — all without central servers.

RetroShare uses a friend-to-friend (F2F) network model. Rather than connecting to arbitrary peers (as in BitTorrent or Tox), RetroShare only connects to peers you have explicitly authenticated by exchanging PGP keys. This creates a web of trust where you know the identity of every peer you communicate with, and your traffic is routed through friends-of-friends rather than anonymous intermediaries.

This F2F model provides strong identity verification but limits network size and requires manual key exchange — you must somehow get your PGP key to your contact, typically through a pre-existing secure channel. For a tight-knit community building an alternative network, this is a reasonable tradeoff. For global anonymous communication, it is more restrictive than other tools.

Jami: Distributed SIP Communication

Jami (formerly Ring, formerly SFLphone) is a free, open-source communication platform that provides voice calls, video calls, messaging, and file transfer using a fully distributed architecture. Jami uses a distributed SIP (Session Initiation Protocol) approach combined with an OpenDHT implementation for peer discovery.

What makes Jami notable is its focus on being a practical replacement for services like Skype or Zoom — it supports high-quality video calls, screen sharing, and conference calls — while requiring no central server. User accounts are cryptographic key pairs stored locally, with the public key registered in the DHT for discoverability.

Jami is available on Linux, Windows, macOS, Android, and iOS, making it one of the most cross-platform P2P communication tools available. It is officially a GNU project and is supported by Savoir-faire Linux, a Canadian free software company.

Building a P2P Application with Python

Simple Peer Discovery Using UDP Broadcast

The first challenge in any P2P application is peer discovery — finding other peers on the network. On a local network, UDP broadcast is the simplest approach. A peer periodically broadcasts a message announcing its presence, and other peers listen for these announcements.

import socket
import threading
import json
import time

DISCOVERY_PORT = 9999
BROADCAST_ADDR = '255.255.255.255'

def announce_presence(name, service_port):
    """Broadcast our presence on the local network."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    message = json.dumps({
        'name': name, 'port': service_port,
        'timestamp': time.time()
    })
    while True:
        sock.sendto(message.encode(), (BROADCAST_ADDR, DISCOVERY_PORT))
        time.sleep(5)
def discover_peers(timeout=30):
    """Listen for peer announcements."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', DISCOVERY_PORT))
    sock.settimeout(timeout)
    peers = {}
    try:
        while True:
            data, addr = sock.recvfrom(1024)
            info = json.loads(data.decode())
            peers[addr[0]] = info
            print(f"Discovered: {info['name']} at {addr[0]}")
    except socket.timeout:
        pass
    return peers

This approach works on any local network — Ethernet, Wi-Fi, or ad-hoc — without requiring any server or configuration. The limitation is that UDP broadcast does not cross network boundaries (routers do not forward broadcasts), so it only works for discovering peers on the same local network segment.

Basic P2P File Sharing Script

Building on peer discovery, here is a minimal P2P file sharing system. One peer serves a file; another peer, having discovered the first through UDP broadcast, downloads it directly:

import socket
import os

def serve_file(filepath, port=8000):
    """Serve a file to any connecting peer."""
    filesize = os.path.getsize(filepath)
    filename = os.path.basename(filepath)
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(('0.0.0.0', port))
    server.listen(5)
    print(f"Serving '{filename}' ({filesize} bytes) on port {port}")
    while True:
        client, addr = server.accept()
        print(f"Peer {addr} connected")
        client.send(f"{filename}|{filesize}".encode())
        with open(filepath, 'rb') as f:
            while chunk := f.read(4096):
                client.send(chunk)
        client.close()
def download_file(peer_ip, port=8000, output_dir='.'):
    """Download a file from a peer."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((peer_ip, port))
    header = sock.recv(1024).decode()
    filename, filesize = header.split('|')
    filesize = int(filesize)
    filepath = os.path.join(output_dir, filename)
    received = 0
    with open(filepath, 'wb') as f:
        while received < filesize:
            data = sock.recv(4096)
            f.write(data)
            received += len(data)
    print(f"Downloaded '{filename}' ({received} bytes)")
    sock.close()

This is deliberately minimal — a production P2P file sharing system would add integrity verification (hash checking), encryption, resumable transfers, parallel downloads from multiple peers (BitTorrent-style), and proper error handling. But the core pattern is here: discover peers, connect directly, transfer data. No server needed.

Considerations for NAT Traversal

The scripts above work beautifully on a local network but will fail across the internet if either peer is behind a NAT router. For a production P2P application, you need to address NAT traversal. Here is a minimal STUN-like approach to discovering your public address:

import socket

def get_public_endpoint(stun_server='stun.l.google.com', port=19302):
    """Discover public IP and port via a STUN-like query."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(5)
    # Simplified STUN binding request
    request = b'\x00\x01\x00\x00' + b'\x21\x12\xa4\x42'
    request += b'\x00' * 12  # Transaction ID
    sock.sendto(request, (stun_server, port))
    try:
        data, addr = sock.recvfrom(1024)
        print(f"STUN server sees us as: {addr}")
    except socket.timeout:
        print("STUN query timed out")
    sock.close()

For a more complete implementation, consider using the pystun3 library, or leverage libp2p — the networking library extracted from IPFS — which handles peer discovery, NAT traversal, encryption, and multiplexing in a comprehensive framework.

The full NAT traversal story involves:

  1. Discovering your NAT type — full cone, restricted cone, port-restricted cone, or symmetric. Each type requires a different traversal strategy.
  2. Exchanging public endpoint information with the peer you want to connect to — this requires some form of signaling channel (a common bootstrapping problem: you need a connection to establish a connection).
  3. Performing the hole punch — both peers simultaneously send packets to create NAT mappings.
  4. Falling back to relay if hole punching fails (symmetric NATs are notoriously difficult to traverse).

For alternative networks, the good news is that these challenges are primarily relevant when connecting across the public internet. On a local mesh or ad-hoc network, all peers have direct Layer 3 reachability and NAT is not an issue. This is yet another advantage of building your own network infrastructure: you get to skip the NAT nightmare entirely.

Bringing It All Together

The technologies in this chapter — ad-hoc wireless, peer-to-peer architectures, delay-tolerant networking, Bluetooth mesh, and P2P applications — form a toolkit for building communication systems that are maximally independent of centralized infrastructure. They are not mutually exclusive; the most resilient alternative networks combine multiple approaches:

The common thread is a design philosophy that treats connectivity as occasional and opportunistic rather than continuous and guaranteed. This is a fundamental shift from how most network software is written, and it requires rethinking assumptions at every layer of the stack.

In the next chapter, we will explore LoRa and LPWAN networks — technologies that extend the range of alternative networks from meters to kilometers, enabling communication across valleys, between villages, and across distances that would require dozens of Wi-Fi hops. Where this chapter gave us the architecture for infrastructure-free networking, the next chapter gives us the reach.

Key Takeaways


← Previous: Mesh Networking Table of Contents Next: LoRa and LPWAN Networks →