Complete Guide to iroh Example Files: 17 Reference Programs for P2P Networking
The iroh repository contains 17 production-ready example programs in iroh/examples/ that demonstrate endpoint creation, encrypted data transfer, connection monitoring, and post-quantum cryptography configurations, all executable via cargo run --example <name>.
The n0-computer/iroh repository ships a comprehensive collection of standalone iroh example files demonstrating how to build peer-to-peer applications with the Rust-based networking library. These examples live in the iroh/examples/ directory and serve as the primary reference for implementing real-world iroh endpoints with various transport configurations, relay modes, and security policies. Each program focuses on a specific networking concept, from basic echo servers to advanced post-quantum key exchange implementations.
How to Run iroh Example Files
All examples compile and execute using Cargo's --example flag. The standard invocation pattern requires specifying the example name, release mode for optimized performance, and optional feature flags:
cargo run --example transfer --release --all-features -- help
This command structure applies uniformly across all 17 programs, allowing you to test connectivity patterns without writing boilerplate code.
Core iroh Example Files by Category
The example suite covers the full spectrum of iroh functionality, organized by operational concern.
Data Transfer and File Operations
iroh/examples/transfer.rs serves as the flagship demonstration, implementing a full-featured data-transfer client and server supporting upload, download, bidirectional transfer, and ping operations. This example showcases Endpoint creation, relay handling, PKARR/DNS address lookup, custom ALPN protocols, and statistics collection with optional qlog support.
Connection Establishment Patterns
Four examples demonstrate connection lifecycle management:
connect.rs– Minimal client establishing remote connections and measuring RTT latency usingEndpoint::connectandConnection::paths.connect-unreliable.rs– Forces direct-only connections by disabling relays viaEndpointArgs::no_relayandAddrFilter::ip_only.listen.rs– Simple server accepting incoming connections and echoing data usingEndpoint::acceptandConnection::accept_bi.listen-unreliable.rs– Server variant that disables relay usage to force direct, potentially unreliable connections.
Endpoint Discovery and Addressing
search.rsdemonstrates remote endpoint discovery via built-in address-lookup services, utilizingEndpoint::lookupandPkarrPublisherfor DNS resolution.remote-info.rsretrieves and displays remote endpoint metadata including ID, relay URLs, and direct addresses throughEndpoint::onlineandEndpoint::addrutilities.
Security and Cryptography
Three examples specialize in modern cryptographic configurations:
prefer-pq-key-exchange.rs– Configures endpoints to prefer post-quantum key exchange algorithms viaQuicTransportConfig::builder().prefer_pq().pq-only-key-exchange.rs– Forces exclusive use of post-quantum key exchange using theonly_pq()builder method.auth-hook.rs– Demonstrates attaching authentication tokens to relay URLs usingRelayMap::with_auth_token.incoming-filter.rs– Shows policy-based connection rejection by inspectingConnection::remote_idbefore accepting.
Connection Monitoring and Diagnostics
screening-connection.rs– Inspects connection paths and RTT before data transfer usingConnection::pathsandPathEvent::Selected.monitor-connections.rs– Continuously watches connection path events and prints live statistics viaConnection::path_eventsandPathEvent::Closedhandling.
Performance and Transport Configuration
custom-transport.rs– Tweaks QUIC transport parameters such asstream_receive_windowandsend_windowusingQuicTransportConfig::builder().0rtt.rs– Demonstrates zero-round-trip-time connections usingConnection::zero_rttwhen servers permit early data.
Simplified Networking Examples
echo.rs– Bidirectional echo client sending payloads and printing replies usingConnection::open_biandSendStream::write_all_chunks.echo-no-router.rs– LAN-local echo implementation running without relays or routers usingEndpointArgs::no_relayand custombind_addrconfiguration.
Common Architectural Patterns
Every iroh example file follows consistent structural conventions that illustrate production-grade application design:
Argument Parsing – All programs use clap::Parser for command-line interface definition, with transfer.rs providing the most comprehensive template.
Endpoint Construction – Examples uniformly invoke Endpoint::builder(presets::Minimal) and customize builders based on flags for relay mode, address lookup, and transport settings.
Async Runtime – Each main function uses #[tokio::main] with tokio::select! patterns to handle graceful shutdown via Ctrl-C cancellation.
Logging Infrastructure – Optional tracing subscribers initialize via iroh::init_tracing, supporting both stdout and file output destinations.
Practical Code Snippets from iroh Examples
Building a Production Endpoint
From iroh/examples/transfer.rs, the standard endpoint initialization pattern:
use iroh::{Endpoint, SecretKey, RelayMode};
use iroh::endpoint::presets;
let secret = SecretKey::generate();
let mut builder = Endpoint::builder(presets::Minimal)
.secret_key(secret)
.relay_mode(RelayMode::Default)
.address_lookup(PkarrPublisher::builder(
"https://pkarr.relay.n0.dev".parse().unwrap(),
));
let endpoint = builder.bind().await?;
println!("Our endpoint ID: {}", endpoint.id());
Establishing Remote Connections
Extracted from iroh/examples/connect.rs:
use iroh::{Endpoint, EndpointAddr, TransportAddr};
let remote_id: EndpointId = "018...".parse()?;
let remote = EndpointAddr::from_parts(
remote_id,
vec![TransportAddr::Relay("https://relay.n0.dev".parse().unwrap())],
);
let conn = endpoint.connect(remote, b"my/alpn").await?;
println!("Connected, RTT: {:?}", conn.paths().next().unwrap().rtt());
Implementing Echo Clients
From iroh/examples/echo.rs:
let conn = endpoint.connect(remote, b"my/echo").await?;
let (mut send, mut recv) = conn.open_bi().await?;
send.write_all(b"ping").await?;
send.finish().await?;
let mut buf = Vec::new();
recv.read_to_end(&mut buf).await?;
println!("Echoed back: {:?}", String::from_utf8_lossy(&buf));
Customizing Transport Windows
From iroh/examples/custom-transport.rs:
use iroh::endpoint::transport::QuicTransportConfig;
let mut cfg = QuicTransportConfig::builder();
cfg = cfg.stream_receive_window(4 * 1024 * 1024);
cfg = cfg.send_window(8 * 1024 * 1024);
let endpoint = Endpoint::builder(presets::Minimal)
.transport_config(cfg.build())
.bind().await?;
Summary
- The iroh example files reside in
iroh/examples/and provide 17 distinct reference implementations for P2P networking patterns. - Examples demonstrate Endpoint configuration, Connection lifecycle management, post-quantum cryptography, and transport-layer customization.
- All programs follow consistent scaffolding using clap for arguments, tokio for async runtime, and tracing for observability.
- Execute any example using
cargo run --example <filename_without_extension> --release. - Reference implementations cover production concerns including relay configuration, address lookup via PKARR/DNS, and connection-path monitoring.
Frequently Asked Questions
Where are the iroh example files located in the repository?
The iroh example files reside in the iroh/examples/ directory within the n0-computer/iroh repository. Each file is a standalone Rust program demonstrating specific library functionality, such as iroh/examples/transfer.rs for data transfer or iroh/examples/echo.rs for bidirectional streaming.
How do I run a specific iroh example with custom features?
Execute examples using Cargo's --example flag: cargo run --example transfer --release --all-features. The --release flag ensures optimized performance, while --all-features enables experimental capabilities like post-quantum cryptography and advanced logging options demonstrated in iroh/examples/custom-transport.rs.
Which iroh example demonstrates post-quantum key exchange?
Two examples specifically address post-quantum cryptography: iroh/examples/prefer-pq-key-exchange.rs configures endpoints to prefer post-quantum algorithms via QuicTransportConfig::builder().prefer_pq(), while iroh/examples/pq-only-key-exchange.rs forces exclusive post-quantum key exchange using the only_pq() method.
Can iroh examples run without internet relays or routers?
Yes, several examples demonstrate direct LAN-only operation. iroh/examples/echo-no-router.rs and iroh/examples/listen-unreliable.rs disable relay functionality using EndpointArgs::no_relay and AddrFilter::ip_only, enabling fully decentralized peer-to-peer connections without external infrastructure.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →