Answer#
A server that hard-codes 0.0.0.0:8080 cannot move to another port without a rebuild, and it is reachable from the whole network whether you meant it or not. Read the address from the environment instead, and choose a safe default.
use std::net::SocketAddr;
/// The address to listen on: LISTEN_ADDR, else a port from PORT (on loopback), else a default.
fn listen_addr(get: impl Fn(&str) -> Option<String>) -> SocketAddr {
if let Some(a) = get("LISTEN_ADDR").and_then(|a| a.parse().ok()) {
return a;
}
if let Some(p) = get("PORT").and_then(|p| p.trim().parse::<u16>().ok()) {
return SocketAddr::from(([127, 0, 0, 1], p)); // behind a web server, loopback only
}
SocketAddr::from(([127, 0, 0, 1], 8080))
}
fn main() {
println!("{}", listen_addr(|k| std::env::var(k).ok()));
println!("{}", listen_addr(|k| (k == "PORT").then(|| "5000".to_string())));
println!("{}", listen_addr(|k| (k == "PORT").then(|| "not a port".to_string())));
println!("{}", listen_addr(|k| (k == "LISTEN_ADDR").then(|| "0.0.0.0:9000".to_string())));
}127.0.0.1:8080
127.0.0.1:5000
127.0.0.1:8080
0.0.0.0:9000The environment is passed in as a function so the code can be tested without changing real environment variables.
| Address | Reachable from | Use when |
|---|---|---|
127.0.0.1:PORT | the same machine only | a reverse proxy (IIS, nginx, Caddy) forwards requests to the app |
0.0.0.0:PORT | every network interface | the app itself accepts outside connections (a container, a simple host) |
[::1]:PORT / [::]:PORT | the IPv6 equivalents | IPv6 setups |
Common mistakes#
- Binding
0.0.0.0on a development machine and leaving a debug server open to the network. - Treating a bad
PORTvalue as a crash. Fall back, or print the value you rejected so the mistake is visible. - Two programs on one port: the second fails to start with "address already in use". Pick a different port or stop the first.
Related questions#
Does the host's firewall matter?#
Yes. Listening on 0.0.0.0 still needs the firewall to allow the port for outside access.
Sources#
- Standard library,
std::net::SocketAddr: https://doc.rust-lang.org/std/net/enum.SocketAddr.html