Skip to content

Commit

Permalink
feat: support network ip
Browse files Browse the repository at this point in the history
  • Loading branch information
TrickyPi committed Oct 25, 2023
1 parent 99fee5a commit bc85465
Show file tree
Hide file tree
Showing 8 changed files with 312 additions and 121 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.DS_Store

/target
180 changes: 168 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "chost"
version = "0.0.7"
version = "0.1.1"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand All @@ -9,4 +9,5 @@ edition = "2021"
clap = { version = "3.0", features = ["derive"] }
hyper = { version = "0.14.26", features = ["full"] }
tokio = { version = "1.27.0", features = ["full"] }
local-ip-address = "0.5.6"
colored = "2.0.0"
46 changes: 46 additions & 0 deletions src/addr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use local_ip_address::local_ip;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};

pub type Port = u16;

pub struct Addr {
local_ip: Ipv4Addr,
network_ip: IpAddr,
}

impl Addr {
pub fn new() -> Self {
return Addr {
local_ip: Ipv4Addr::new(127, 0, 0, 1),
network_ip: local_ip().unwrap(),
};
}
pub fn is_free_port(&self, port: Port) -> Option<(SocketAddr, SocketAddr)> {
let Addr {
local_ip,
network_ip,
} = self;
let local_addr = SocketAddr::new(IpAddr::V4(*local_ip), port);
let network_addr = SocketAddr::new(*network_ip, port);
if TcpListener::bind(local_addr).is_ok() | TcpListener::bind(network_addr).is_ok() {
return Some((local_addr, network_addr));
}
None
}
pub fn get_address(&self, port: Port) -> (SocketAddr, SocketAddr) {
if let Some(addr) = self.is_free_port(port) {
return addr;
}
let start = 7878;
let end = 8989;
for other_port in start..end {
if other_port == port {
continue;
}
if let Some(addr) = self.is_free_port(other_port) {
return addr;
}
}
panic!("the {} port is not free, chost try to find a free port from {} to {}, but also didn\'t find a free port, please use --port flag to specify a free port", port, start, end)
}
}
22 changes: 0 additions & 22 deletions src/ip_port.rs

This file was deleted.

0 comments on commit bc85465

Please sign in to comment.