Small Rust scripts
at main 48 lines 1.1 kB view raw
1#!/usr/bin/env -S cargo +nightly -Zscript 2 3--- 4[package] 5edition = "2024" 6[dependencies] 7argh = "0.1" 8--- 9 10use std::net::{TcpStream, ToSocketAddrs}; 11use std::process; 12use std::time::Duration; 13 14use argh::FromArgs; 15 16#[derive(FromArgs)] 17#[argh(description = "Check if a TCP port is reachable.")] 18struct App { 19 #[argh(option, description = "timeout in seconds.", default = "5")] 20 timeout: u64, 21 22 #[argh(positional, description = "host to connect to.")] 23 host: String, 24 25 #[argh(positional, description = "port to connect to.")] 26 port: u16, 27} 28 29fn main() { 30 let app: App = argh::from_env(); 31 let address = format!("{}:{}", app.host, app.port); 32 let timeout = Duration::from_secs(app.timeout); 33 34 let addrs: Vec<_> = address 35 .to_socket_addrs() 36 .expect("failed to resolve address") 37 .collect(); 38 39 for addr in &addrs { 40 if TcpStream::connect_timeout(addr, timeout).is_ok() { 41 println!("reachable"); 42 process::exit(0); 43 } 44 } 45 46 println!("unreachable"); 47 process::exit(1); 48}