You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12 lines
383B

  1. use std::net::TcpListener;
  2. pub fn get_available_port(avoid: u16) -> Option<u16> {
  3. // Start after "well-known" ports (0–1023) as they require superuser
  4. // privileges on UNIX-like operating systems.
  5. (1024..9000).find(|port| *port != avoid && port_is_available(*port))
  6. }
  7. pub fn port_is_available(port: u16) -> bool {
  8. TcpListener::bind(("127.0.0.1", port)).is_ok()
  9. }