FAQ - Help and questions

How should a Rust web server choose its port and address?

#web#deployment#configurationpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Read the address from configuration, not from the source code. Accept a full LISTEN_ADDR, else a PORT bound to loopback, else a default. Behind a reverse proxy listen on 127.0.0.1 so only the proxy can reach the app; listen on 0.0.0.0 only when the app must accept outside connections itself.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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())));
}
text
127.0.0.1:8080
127.0.0.1:5000
127.0.0.1:8080
0.0.0.0:9000

The environment is passed in as a function so the code can be tested without changing real environment variables.

AddressReachable fromUse when
127.0.0.1:PORTthe same machine onlya reverse proxy (IIS, nginx, Caddy) forwards requests to the app
0.0.0.0:PORTevery network interfacethe app itself accepts outside connections (a container, a simple host)
[::1]:PORT / [::]:PORTthe IPv6 equivalentsIPv6 setups

Common mistakes#

  • Binding 0.0.0.0 on a development machine and leaving a debug server open to the network.
  • Treating a bad PORT value 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet