Error: Os { code: 13, kind: PermissionDenied, message: Permission denied }

I am getting a permissions error when running cargo run on certain programs. For example a "hello world" program runs with no issues but something like the following gives me a permissions error:

#![allow(unused_variables)]
use std::net::{TcpListener, TcpStream}; 

fn handle_client(stream: TcpStream) {
    // do something
}
 
fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:80")?;
 
    
    for stream in listener.incoming() {
        handle_client(stream?);
    }
    
    Ok(())
}

Error: Os { code: 13, kind: PermissionDenied, message: "Permission denied" }

Is this a Linux issue or should I be looking at permissions in my home folder for .cargo folder or something similar? This is the first time seeing this error.

Again, running cargo run on something like this

fn main() {
    println!("Hello, world!");
}

doesn't give me the error.
I am running Ubuntu 21.10

The full error message will probably tell you where the error happened.
You will then notice it is on the bind line.
That's because on Linux ports below 1024 require special privileges (either being root or the net_bind_service capability).

If you use "127.0.0.1:8000" it will most likely work (unless there's something else already running on that port). Your server will listen on port 8000 then.

3 Likes

You can't bind to ports under 1024 (or 1000? I don't remember) if you aren't admin/root. So you're getting "permission denied".

2 Likes

Oh I see, that solved it and makes sense now. :smiley: Thanks for the help.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.