nopserv/nopserv.rs

67 lines
1.4 KiB
Rust

use std::io::prelude::*;
use std::net::TcpListener;
use std::env::args;
use std::process::exit;
use std::thread;
static MESSAGE:&[u8] = b"nope\n";
fn main() {
let argv:Vec<String> = args().collect();
if argv.len() < 2 {
eprintln!("usage: nopserv [ports]...");
exit(1);
}
let mut ports:Vec<u16> = Vec::new();
for arg in argv[1..].iter() {
let argparts:Vec<&str> = arg.splitn(2,"-").collect();
if argparts.len() > 1 {
let start = match argparts[0].parse::<u16>() {
Err(_) => exit(1),
Ok(n) => n,
};
let end = match argparts[1].parse::<u16>() {
Err(_) => exit(1),
Ok(n) => n,
};
for i in start..end {
ports.push(i);
}
ports.push(end);
} else {
match argparts[0].parse::<u16>() {
Err(_) => exit(1),
Ok(n) => ports.push(n),
};
}
}
let mut threadhandles:Vec<thread::JoinHandle<()>> = Vec::new();
for port in ports {
let handle = thread::spawn(move || {
match TcpListener::bind(&format!("[::]:{}",port)) {
Err(why) => {
eprintln!("failed to listen on port {}: {}",port,why);
},
Ok(listener) => {
loop {
match listener.accept() {
Err(_) => (),
Ok((mut stream,address)) => {
let _ = stream.write_all(MESSAGE);
println!("closing connection to {}",address);
},
};
}
},
};
});
threadhandles.push(handle);
}
while let Some(handle) = threadhandles.pop() {
let _ = handle.join();
}
}