Skip to content

Instantly share code, notes, and snippets.

@killercup
Created January 12, 2017 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killercup/2849a80c39a1dd1358fa5cbfce2718b6 to your computer and use it in GitHub Desktop.
Save killercup/2849a80c39a1dd1358fa5cbfce2718b6 to your computer and use it in GitHub Desktop.
Ping ALL the machines in a subnet
use std::collections::BTreeMap;
use std::net::Ipv4Addr;
use std::thread;
use std::process::{Command, Stdio};
fn main() {
let subnet: u8 = std::env::args()
.skip(1)
.next()
.unwrap_or("20".into())
.parse()
.expect("failed to parse to byte");
let check_hosts: Vec<_> = (1..255)
.map(|i| {
let ip = Ipv4Addr::new(192, 168, subnet, i);
let worker = thread::spawn(move || {
Command::new("ping")
.args(&["-c", "1", "-t", "2", &format!("{}", &ip)])
.stdout(Stdio::null())
.spawn()
.expect("failed to execute child")
.wait()
.expect("failed to wait on child")
.success()
});
(ip, worker)
})
.collect();
let available_hosts: BTreeMap<Ipv4Addr, bool> = check_hosts.into_iter()
.map(|(ip, worker)| {
let exists = worker.join().expect("failed to get worker result");
(ip, exists)
})
.collect();
println!("{:#?}", available_hosts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment