Port Scan Code Fails to Print Range

All,

I am new to Rust and found a bug in this code. The code below compiles and returns the start port, but if there is a port range, it simply repeats the start code value - how can I return the accurate port numbers found in the range specified?

use std::env;
use std::net::TcpStream;

/// Program will take three command line arguments (Host, IP, and a start and stop port).
///
/// port_scan.exe xxx.xxx.x.xxx, 80, 85
///
///
///
///

fn main() {

let args : Vec<String> = env::args().collect();

if args.len() == 4 {

    let ip = &args[1];

    if let Ok(start_port) = &args[2].parse::<i32>(){

        if let Ok(stop_port) = &args[3].parse::<i32>(){
            
            let mut port = *start_port;

            while port <= *stop_port{

                let result = TcpStream::connect(format!("{}:{}", ip, port));

                match result{
                    Ok(_stream) => {
                        println!("Port {} open", start_port);
                    },
                    Err(_e) => {}
                }

                port += 1;
            }
        }else{
            println!("Can't parse stop port.")
        }

    }else{
        println!("Can't parse start port.")
    }

}else{
    println!("Command requires 3 arguments");
}

}

C:\RUST\port_scan\target\release>port_scan 127.0.0.1 49664 49665
Port 49664 open
Port 49664 open

Confirmed ports 49664 49665 are open - should be

C:\RUST\port_scan\target\release>port_scan 127.0.0.1 49664 49665
Port 49664 open
Port 49665 open

The quick fix is:

-    println!("Port {} open", start_port);
+    println!("Port {} open", port);

But here's how I might write a quick and dirty version.

1 Like

Thank you for the excellent points in making the code even better! Dave

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.