I’m trying to build an nmap-like CLI port scanning tool in Rust. I want to ensure that if the user doesn’t pass the optional –ports flag in their command, the tool scans a range of commonly used ports and outputs their state, service and other relevant information. However, when no –ports flag is passed, I’m scanning a very large number of ports instead of the commonly used ports. This is what the output looks like for the command cargo run -- --host scanme.nmap.org
:
...
[2024-06-12T06:19:42Z INFO ferric] Port 264 is filtered! Service: Unknown
[2024-06-12T06:19:42Z INFO ferric] Port 994 is filtered! Service: Unknown
[2024-06-12T06:19:42Z INFO ferric] Port 995 is filtered! Service: Unknown
[2024-06-12T06:19:42Z INFO ferric] Port 997 is filtered! Service: Unknown
[2024-06-12T06:19:42Z INFO ferric] Port 988 is filtered! Service: Unknown
[2024-06-12T06:19:42Z INFO ferric] Port 976 is filtered! Service: Unknown
[2024-06-12T06:19:42Z INFO ferric] Port 984 is filtered! Service: Unknown
...
I tried modifying my parse_ports function to check if there is no –ports flag in the command, but this doesn’t seem to work. Should I use a match statement instead? Here is the parse_ports function:
const COMMON_PORTS: &[u16] = &[80, 443, 22, 21, 25, 110, 143, 3306, 5432, 27017, 6379, 8080];
// Function to parse ports
`
fn parse_ports(ports: Option<&str>) -> Result<Vec<u16>, String> {
if let Some(port_str) = ports {
let mut ports_vec = Vec::new();
for part in port_str.split(',') {
if let Some(range) = part.split_once('-') {
let start: u16 = range.0.parse().map_err(|e| format!("Invalid port range: {}", e))?;
let end: u16 = range.1.parse().map_err(|e| format!("Invalid port range: {}", e))?;
if start > end {
return Err(format!("Invalid port range: {} - {}", start, end));
}
ports_vec.extend(start..=end);
} else {
let port: u16 = part.parse().map_err(|_| format!("Invalid port: {}", part))?;
ports_vec.push(port);
}
}
Ok(ports_vec)
} else {
Ok(COMMON_PORTS.to_vec())
}
}
rajan07 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.