-
Notifications
You must be signed in to change notification settings - Fork 291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Get An Unused TCP/IP (or UDP) Port #500
Comments
This works, but it can fail due to TOCTOU - someone else can snatch the port before you open the real socket. A solution would be to return the socket you used for probing, e.g. in Option, or to use retries. |
This works only due to For example this does not work on OS X and I have no idea if this will work on Windows. A better approach that works on all OSes (solving the TOCTOU problem as well) is the following (not tested though!!): fn listen_available_port() -> Option<TcpListener> {
for port in (1025..65535) {
match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => return Some(l),
_ => {}
}
}
None
} Still this approach does not take into account other |
docs |
This is a duplicate of #123 , but I was hoping for a slightly different solution than the one provided there.
I was hoping to get a free port so I can make a temporary postgres database listen on it while I am running database tests.
I found a nice answer on this blog: https://elliotekj.com/2017/07/25/find-available-tcp-port-rust/
Here is how I look for available ports:
I have made one slight change;
get_available_port
checks all possible user-assignable ports.The text was updated successfully, but these errors were encountered: