Tutorials & Examples
Learn to build Tor-integrated applications with stem through practical, production-ready examples. From basic connections to advanced hidden service deployment.
Before using stem, ensure you have Tor installed and configured with a control port. The control port allows external applications to communicate with the Tor process.
🔧 Tor Installation
Install Tor via your package manager or from torproject.org
⚙️ Control Port
Enable the control port in your torrc configuration file
🦀 Rust Toolchain
Rust 1.88+ (edition 2024) with the Tokio runtime
Add the following lines to your torrc file to enable the control port:
# Enable the control port for local connections
ControlPort 9051
# Cookie authentication (recommended for local use)
CookieAuthentication 1
# Alternative: Password authentication
# HashedControlPassword 16:872860B76453A77D60CA2BB8C1A7042072093276A3D701AD684053EC4CCookie authentication is preferred for local connections as it doesn't require storing passwords. The cookie file is automatically created with restricted permissions.
[dependencies]
stem = "2"
tokio = { version = "1", features = ["full"] }Establish a connection to Tor and authenticate. The controller automatically detects the best authentication method available.
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
println!("Connected to Tor {}", controller.get_version().await?);
Ok(())
}Connected to Tor 0.4.9.12
stem supports all standard Tor authentication methods:
| Method | Description | Configuration |
|---|---|---|
SAFECOOKIE | Challenge-response authentication (most secure) | CookieAuthentication 1 |
COOKIE | File-based authentication token | CookieAuthentication 1 |
HASHEDPASSWORD | Password-based authentication | HashedControlPassword ... |
NULL | No authentication (not recommended) | Default when no auth configured |
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let options = ConnectOptions {
password: Some("your_password".to_string()),
..ConnectOptions::default()
};
let controller = connect(options).await?;
println!(
"Authenticated against tor {}",
controller.get_version().await?
);
Ok(())
}use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let options = ConnectOptions {
control_port: None,
control_socket: Some("/var/run/tor/control".into()),
..ConnectOptions::default()
};
let controller = connect(options).await?;
println!("Tor process ID: {}", controller.get_pid().await?);
Ok(())
}Query cumulative traffic statistics from your relay. These values represent total bytes transferred since Tor started.
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
let bytes_read = controller.get_info("traffic/read").await?;
let bytes_written = controller.get_info("traffic/written").await?;
println!("Traffic Statistics:");
println!(" Downloaded: {bytes_read} bytes");
println!(" Uploaded: {bytes_written} bytes");
Ok(())
}Traffic Statistics: Downloaded: 7856100 bytes Uploaded: 725006 bytes
The get_info method provides access to numerous Tor metrics:
| Key | Description | Type |
|---|---|---|
traffic/read | Total bytes downloaded | Integer |
traffic/written | Total bytes uploaded | Integer |
version | Tor version string | String |
circuit-status | Active circuit information | Multi-line |
stream-status | Active stream information | Multi-line |
address | Best guess at external IP | IP Address |
fingerprint | Relay fingerprint (if relay) | Hex String |
A complete example that queries multiple metrics and formats them for display:
use stem::{ConnectOptions, connect};
fn format_bytes(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
const GB: f64 = MB * 1024.0;
match bytes as f64 {
size if size >= GB => format!("{:.2} GB", size / GB),
size if size >= MB => format!("{:.2} MB", size / MB),
size if size >= KB => format!("{:.2} KB", size / KB),
_ => format!("{bytes} B"),
}
}
async fn traffic(controller: &stem::Controller, direction: &str) -> stem::Result<u64> {
let total = controller.get_info(&format!("traffic/{direction}")).await?;
Ok(total.trim().parse().unwrap_or(0))
}
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
let version = controller.get_version().await?;
let pid = controller.get_pid().await?;
let read = traffic(&controller, "read").await?;
let written = traffic(&controller, "written").await?;
println!("Version: {version}");
println!("Process ID: {pid}");
println!("Downloaded: {}", format_bytes(read));
println!("Uploaded: {}", format_bytes(written));
Ok(())
}Use the ExitNodes configuration option to specify which countries Tor should exit through. Country codes follow the ISO 3166-1 alpha-2 standard enclosed in braces.
use stem::enumerations::Signal;
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
controller.set_conf("ExitNodes", "{de}").await?;
controller.signal(&Signal::Newnym).await?;
println!("New circuits will exit through Germany");
controller.reset_conf(&["ExitNodes"]).await?;
Ok(())
}Restricting exit nodes reduces anonymity by limiting the pool of available relays. Use this feature only when geographic location is essential for your use case.
| Code | Country | Code | Country |
|---|---|---|---|
{us} | United States | {de} | Germany |
{gb} | United Kingdom | {fr} | France |
{nl} | Netherlands | {ch} | Switzerland |
{se} | Sweden | {jp} | Japan |
Combine stem with an HTTP client that supports SOCKS5 proxies to make requests through Tor:
[dependencies]
reqwest = { version = "0.13", features = ["socks"] }use std::time::Duration;
use stem::enumerations::Signal;
use stem::{ConnectOptions, connect};
const SOCKS_PROXY: &str = "socks5h://127.0.0.1:9050";
async fn query_through_tor(url: &str) -> Result<String, reqwest::Error> {
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::all(SOCKS_PROXY)?)
.timeout(Duration::from_secs(30))
.build()?;
client.get(url).send().await?.text().await
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let controller = connect(ConnectOptions::default()).await?;
controller.set_conf("ExitNodes", "{de}").await?;
controller.signal(&Signal::Newnym).await?;
tokio::time::sleep(Duration::from_secs(5)).await;
let response = query_through_tor("https://check.torproject.org/api/ip").await?;
println!("Exit IP information: {response}");
Ok(())
}Iterate through multiple countries for testing or data collection:
use std::time::Duration;
use stem::enumerations::Signal;
use stem::{ConnectOptions, connect};
const COUNTRIES: [(&str, &str); 4] = [
("{us}", "United States"),
("{de}", "Germany"),
("{jp}", "Japan"),
("{nl}", "Netherlands"),
];
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
for (code, name) in COUNTRIES {
println!("Switching to {name} ({code})");
controller.set_conf("ExitNodes", code).await?;
controller.signal(&Signal::Newnym).await?;
tokio::time::sleep(Duration::from_secs(3)).await;
}
controller.reset_conf(&["ExitNodes"]).await?;
println!("Reset to the default exit selection");
Ok(())
}For advanced use cases, you can inspect and manage circuits directly:
use std::time::Duration;
use stem::enumerations::CircStatus;
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
for circuit in controller.get_circuits().await? {
if circuit.status != CircStatus::Built {
continue;
}
println!("Circuit {} ({} hops):", circuit.id, circuit.path.len());
for (fingerprint, nickname) in &circuit.path {
println!(" {fingerprint:?} {nickname:?}");
}
}
let timeout = Some(Duration::from_secs(30));
let circuit_id = controller.new_circuit(None, None, true, timeout).await?;
println!("Created circuit {circuit_id}");
controller.close_circuit(&circuit_id, "").await?;
println!("Closed circuit {circuit_id}");
Ok(())
}Tor emits various events that you can subscribe to. Each event type provides different information about Tor's operation:
| Event | Description | Frequency |
|---|---|---|
Bw | Bandwidth usage (bytes read/written) | Every second |
Circ | Circuit status changes | On change |
Stream | Stream status changes | On change |
Notice | Notice-level log messages | On occurrence |
Warn | Warning-level log messages | On occurrence |
Err | Error-level log messages | On occurrence |
Monitor Tor's bandwidth usage in real-time. Bandwidth events are emitted every second with the bytes transferred:
use stem::events::{EventData, EventType};
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
let (_, mut events) = controller.subscribe(&[EventType::Bw]).await?;
let (mut total_read, mut total_written) = (0, 0);
while let Some(event) = events.recv().await {
let EventData::Bandwidth(bandwidth) = event.data else {
continue;
};
total_read += bandwidth.read;
total_written += bandwidth.written;
println!(
"down {:>8} B/s up {:>8} B/s total: down {total_read} up {total_written}",
bandwidth.read, bandwidth.written
);
}
Ok(())
}down 0 B/s up 536 B/s total: down 0 up 536 down 1608 B/s up 1608 B/s total: down 1608 up 2144 down 0 B/s up 536 B/s total: down 1608 up 2680
Track circuit lifecycle events including creation, extension, and closure:
use stem::enumerations::CircStatus;
use stem::events::{EventData, EventType};
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
let (_, mut events) = controller.subscribe(&[EventType::Circ]).await?;
while let Some(event) = events.recv().await {
let EventData::Circuit(circuit) = event.data else {
continue;
};
let label = match circuit.status {
CircStatus::Launched => "LAUNCHED",
CircStatus::Built => "BUILT",
CircStatus::Extended => "EXTENDED",
CircStatus::Failed => "FAILED",
CircStatus::Closed => "CLOSED",
_ => "OTHER",
};
println!(
"{label} circuit {} ({} hops)",
circuit.id,
circuit.path.len()
);
}
Ok(())
}subscribe returns a channel receiver. Combine it with tokio::select! to handle several events and shutdown signals in one task:
use stem::events::{EventData, EventType};
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
let (_, mut events) = controller
.subscribe(&[EventType::Bw, EventType::Circ, EventType::Notice])
.await?;
loop {
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
Some(event) = events.recv() => match event.data {
EventData::Bandwidth(bandwidth) if bandwidth.read + bandwidth.written > 0 => {
println!("[BW] down {} up {}", bandwidth.read, bandwidth.written);
}
EventData::Circuit(circuit) => {
println!("[CIRC] {} {:?}", circuit.id, circuit.status);
}
EventData::Log(log) => println!("[{:?}] {}", log.runlevel, log.message),
_ => {}
},
}
}
controller.close().await;
Ok(())
}The Tor network publishes several types of descriptors containing relay information:
The consensus is the authoritative document listing all relays in the network:
use stem::descriptor::Descriptor;
use stem::descriptor::remote::DescriptorDownloader;
#[tokio::main]
async fn main() -> stem::Result<()> {
let downloader = DescriptorDownloader::new();
let documents = downloader.get_consensus_validated(None, false).await?;
for document in documents {
let Descriptor::NetworkStatusV3(consensus) = document else {
continue;
};
println!("Valid after: {:?}", consensus.valid_after);
println!("Valid until: {:?}", consensus.valid_until);
println!("Total relays: {}", consensus.routers.len());
for flag in ["Guard", "Exit", "Fast", "Stable"] {
let count = consensus
.routers
.values()
.filter(|router| router.common().flags.iter().any(|name| name == flag))
.count();
println!("{flag}: {count}");
}
}
Ok(())
}Valid after: Some(2026-10-01T23:00:00) Valid until: Some(2026-10-02T02:00:00) Total relays: 9463 Guard: 5229 Exit: 3071 Fast: 9104 Stable: 8120
Analyze server descriptors to find the highest-bandwidth exit relays:
use stem::descriptor::Descriptor;
use stem::descriptor::remote::DescriptorDownloader;
#[tokio::main]
async fn main() -> stem::Result<()> {
let descriptors = DescriptorDownloader::new()
.get_server_descriptors(&[])?
.run()
.await?;
let mut exits = Vec::new();
for descriptor in descriptors {
let Descriptor::RelayServer(relay) = descriptor else {
continue;
};
let server = &relay.common;
if !server.exit_policy.is_exiting_allowed() {
continue;
}
let bandwidths = [
server.average_bandwidth,
server.burst_bandwidth,
server.observed_bandwidth,
];
let advertised = bandwidths.into_iter().flatten().min().unwrap_or(0);
exits.push((server.nickname.clone().unwrap_or_default(), advertised));
}
exits.sort_by_key(|exit| std::cmp::Reverse(exit.1));
for (rank, (nickname, bandwidth)) in exits.iter().take(10).enumerate() {
let megabytes = *bandwidth as f64 / (1024.0 * 1024.0);
println!("{:>2}. {nickname} - {megabytes:.2} MB/s", rank + 1);
}
Ok(())
}Parse descriptors from Tor's cached files or your own archives:
use stem::descriptor::{Descriptor, DigestEncoding, DigestHash, DocumentHandler, parse_path};
fn main() -> stem::Result<()> {
let path = "/var/lib/tor/cached-descriptors".as_ref();
for file in parse_path(path, None, false, DocumentHandler::Entries)? {
let Descriptor::RelayServer(relay) = file.descriptor else {
continue;
};
let server = &relay.common;
println!("Nickname: {:?}", server.nickname);
println!("Address: {:?}:{:?}", server.address, server.or_port);
println!("Published: {:?}", server.published);
println!(
"Digest: {}",
relay.digest(DigestHash::Sha1, DigestEncoding::Hex)?
);
println!(
"Allows exiting: {}",
server.exit_policy.is_exiting_allowed()
);
println!("Summary: {}", server.exit_policy.summary());
}
Ok(())
}Parse and evaluate exit policies to determine what traffic a relay allows:
use stem::exit_policy::{ExitPolicy, ExitPolicyRule, MicroExitPolicy};
fn main() -> stem::Result<()> {
let policy = ExitPolicy::new(&[
"accept *:80",
"accept *:443",
"accept *:8080-8090",
"reject *:*",
])?;
for port in [80, 443, 22, 8085] {
let allowed = policy.can_exit_to(Some("93.184.216.34"), Some(port), false)?;
println!(
"Port {port}: {}",
if allowed { "allowed" } else { "blocked" }
);
}
println!("Summary: {}", policy.summary());
println!("Allows exiting: {}", policy.is_exiting_allowed());
let rule = ExitPolicyRule::new("reject 10.0.0.0/8:*")?;
println!("Rule accepts: {}", rule.is_accept);
let micro = MicroExitPolicy::new("accept 80,443,8080-8090")?;
println!("Micro policy: {micro}");
Ok(())
}Port 80: allowed Port 443: allowed Port 22: blocked Port 8085: allowed Summary: accept 80, 443, 8080-8090 Allows exiting: true Rule accepts: false Micro policy: accept 80,443,8080-8090
Parse Tor version strings and compare them for feature detection:
use stem::Version;
fn main() -> stem::Result<()> {
let current = Version::new("0.4.7.10")?;
let newer = Version::new("0.4.8.0")?;
let development = Version::new("0.4.7.10-dev")?;
println!("{current} < {newer}: {}", current < newer);
println!("{current} == {development}: {}", current == development);
println!(
"{current} >= 0.4.0.0: {}",
current >= Version::new("0.4.0.0")?
);
if current >= Version::new("0.3.2.1")? {
println!("Tor {current} supports v3 onion services");
}
Ok(())
}Validate Tor-specific identifiers like fingerprints and nicknames:
use stem::validation::{is_valid_fingerprint, is_valid_nickname};
fn main() {
for fingerprint in [
"9695DFC35FFEB861329B9F1AB04C46397020CE31",
"not-a-fingerprint",
] {
println!(
"{fingerprint}: {}",
is_valid_fingerprint(fingerprint, false)
);
}
for nickname in ["MyRelay123", "way-too-long-nickname-for-tor"] {
println!("{nickname}: {}", is_valid_nickname(nickname));
}
}Compute cryptographic digests used by Tor for descriptor identification:
use stem::descriptor::{DigestEncoding, DigestHash, encode_digest, hash_bytes};
fn main() {
let content = b"Example descriptor content";
let sha1 = hash_bytes(DigestHash::Sha1, content);
println!(
"SHA-1 hex: {}",
encode_digest(&sha1, DigestEncoding::Hex)
);
println!(
"SHA-1 base64: {}",
encode_digest(&sha1, DigestEncoding::Base64)
);
let sha256 = hash_bytes(DigestHash::Sha256, content);
println!(
"SHA-256 hex: {}",
encode_digest(&sha256, DigestEncoding::Hex)
);
}Read and modify Tor's runtime configuration:
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
let socks_port = controller.get_conf("SocksPort").await?;
println!("Current SOCKS port: {socks_port:?}");
controller.set_conf("MaxCircuitDirtiness", "600").await?;
controller.reset_conf(&["MaxCircuitDirtiness"]).await?;
Ok(())
}List and inspect active streams and circuits:
use stem::enumerations::{CircStatus, StreamStatus};
use stem::{ConnectOptions, connect};
#[tokio::main]
async fn main() -> stem::Result<()> {
let controller = connect(ConnectOptions::default()).await?;
println!("Streams:");
for stream in controller.get_streams().await? {
let succeeded = stream.status == StreamStatus::Succeeded;
println!(
" {} {} -> {}:{} (circuit {:?}, succeeded: {succeeded})",
stream.id, stream.target, stream.target_address, stream.target_port, stream.circ_id
);
}
println!("Circuits:");
for circuit in controller.get_circuits().await? {
let built = circuit.status == CircStatus::Built;
println!(
" {} ({} hops, built: {built})",
circuit.id,
circuit.path.len()
);
}
Ok(())
}