Created
July 10, 2025 05:53
-
-
Save moriarty99779/82d4574a9d007d0c253e3580abc83a36 to your computer and use it in GitHub Desktop.
Rust Code to Find Open Ports on Subnet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::net::{TcpStream, Ipv4Addr, SocketAddr}; | |
| use std::time::Duration; | |
| use std::thread; | |
| const TIMEOUT: Duration = Duration::from_secs(1); | |
| const PORT_RANGE: std::ops::Range<u16> = 1..1024; | |
| fn main() { | |
| let local_ip = get_local_ip().expect("Could not get local IP address"); | |
| let subnet = get_subnet(&local_ip); | |
| println!("Scanning subnet: {}", subnet); | |
| let mut threads = vec![]; | |
| for i in 1..=254 { | |
| let ip = format!("{}.{}.{}.{}", subnet.0, subnet.1, subnet.2, i); | |
| let ip = ip.parse::<Ipv4Addr>().unwrap(); | |
| let handle = thread::spawn(move || { | |
| scan_ports(&ip); | |
| }); | |
| threads.push(handle); | |
| } | |
| for handle in threads { | |
| handle.join().unwrap(); | |
| } | |
| } | |
| fn scan_ports(ip: &Ipv4Addr) { | |
| let open_ports: Vec<u16> = PORT_RANGE.clone().filter_map(|port| { | |
| let socket_addr = SocketAddr::new((*ip).into(), port); | |
| if is_port_open(&socket_addr) { | |
| Some(port) | |
| } else { | |
| None | |
| } | |
| }).collect(); | |
| if !open_ports.is_empty() { | |
| println!("Open ports on {}: {:?}", ip, open_ports); | |
| } | |
| } | |
| fn is_port_open(socket_addr: &SocketAddr) -> bool { | |
| let stream = TcpStream::connect_timeout(socket_addr, TIMEOUT); | |
| match stream { | |
| Ok(_) => true, | |
| Err(_) => false, | |
| } | |
| } | |
| fn get_local_ip() -> Option<Ipv4Addr> { | |
| let ip = local_ip_address::local_ip().ok()?; | |
| Some(ip) | |
| } | |
| fn get_subnet(local_ip: &Ipv4Addr) -> Ipv4Addr { | |
| Ipv4Addr::new(local_ip.octets()[0], local_ip.octets()[1], local_ip.octets()[2], 0) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment