赞
踩
要实现端口扫描, 只需要遍历端口, 然后尝试连接, 成功就表示是开放的
表示接收到的命令行参数, 有ip地址, 要使用的线程数(每次用多少线程来同时请求端口)
扫描端口, 尝试连接, 成功了就在屏幕输出一个 .
接收命令行参数, 创建Arguments对象, 创建时会判断参数个数, 如果不合规就会退出程序;
开 指定线程数 个端口, 然后开 指定线程数 个线程去同时请求这些的端口
- use std::env;
- use std::io::{ self, Write };
- use std::net::{ IpAddr, TcpStream };
- use std::str::FromStr;
- use std::process;
- use std::sync::mpsc::{ Sender, channel };
- use std::thread;
- // 最大端口
- const MAX: u16 = 65535;
- struct Arguments {
- flag: String,
- ipaddr: IpAddr, // ip地址
- threads: u16, // 线程数
- }
- impl Arguments {
- fn new(args: &[String]) -> Result<Arguments, &'static str> {
- if args.len() < 2 {
- return Err("not enough arguments");
- } else if args.len() > 4 {
- return Err("too many arguments");
- }
- let f = args[1].clone();
- if let Ok(ipaddr) = IpAddr::from_str(&f) {
- return Ok(Arguments { flag: String::from(""), ipaddr, threads: 4 });
- } else {
- let flag = args[1].clone();
- if flag.contains("-h") || flag.contains("-help") || args.len() == 2 {
- println!(
- "Usage: -j to select how many threads you want\r\n -h or -help to show this help message"
- );
- return Err("help");
- } else if flag.contains("-h") || flag.contains("-help") {
- return Err("too many arguments");
- } else if flag.contains("-j") {
- let ipaddr = match IpAddr::from_str(&args[3]) {
- Ok(s) => s,
- Err(_) => {
- return Err("not a valid IpAddr;must be ipv4 or ipv6");
- }
- };
- let threads = match args[2].parse::<u16>() {
- Ok(s) => s,
- Err(_) => {
- return Err("failed to parse thread number");
- }
- };
- return Ok(Arguments { threads, flag, ipaddr });
- } else {
- return Err("Invalid syntax");
- }
- }
- }
- }
- // 扫描端口
- fn scan(tx: Sender<u16>, start_port: u16, addr: IpAddr, num_threads: u16) {
- let mut port: u16 = start_port + 1;
- loop {
- match TcpStream::connect((addr, port)) {
- Ok(_) => {
- print!(".");
- io::stdout().flush().unwrap();
- tx.send(port).unwrap();
- }
- Err(_) => {}
- }
- if MAX - port <= num_threads {
- break;
- }
- port += num_threads;
- }
- }
- fn main() {
- // 接收命令行参数
- let args: Vec<String> = env::args().collect();
- let program = args[0].clone();
- let arguments = Arguments::new(&args).unwrap_or_else(|err| {
- if err.contains("help") {
- process::exit(0);
- } else {
- eprintln!("{} problem parsing arguments: {}", program, err);
- process::exit(0);
- }
- });
- let num_threads = arguments.threads;
- let addr = arguments.ipaddr;
- let (tx, rx) = channel();
- for i in 0..num_threads {
- let tx = tx.clone();
- thread::spawn(move || {
- scan(tx, i, addr, num_threads);
- });
- }
- let mut out = vec![];
- drop(tx);
- for p in rx {
- out.push(p);
- }
- println!("");
- out.sort();
- for v in out {
- println!("{} is open", v);
- }
- }
- cargo run -- -h
- cargo run -- -j 1000 192.168.1.1
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。