tcp.rs 488 B

12345678910111213141516171819202122232425
  1. use std::net::TcpListener;
  2. use rand;
  3. use rand::distributions::{Distribution, Uniform};
  4. pub fn get_available_port() -> Option<u16> {
  5. let mut rng = rand::thread_rng();
  6. let die = Uniform::from(8000..9000);
  7. for _i in 0..100 {
  8. let port = die.sample(&mut rng);
  9. if port_is_available(port) {
  10. return Some(port);
  11. }
  12. }
  13. None
  14. }
  15. pub fn port_is_available(port: u16) -> bool {
  16. match TcpListener::bind(("127.0.0.1", port)) {
  17. Ok(_) => true,
  18. Err(_) => false,
  19. }
  20. }