gscan/
lib.rs

1use tokio::net::TcpStream;
2use tokio::task;
3use std::net::{IpAddr, SocketAddr};
4use std::time::Duration;
5
6pub struct ScanResult {
7    pub ip: IpAddr,
8    pub ports: Vec<u16>,
9}
10pub fn version() -> &'static str {
11    "GSCAN VERSION - 0.1.4"
12}
13
14async fn scan_port(ip: IpAddr, port: u16) -> bool {
15    let socket = SocketAddr::new(ip, port);
16
17    let timeout : Duration = Duration::from_millis(200);
18    let connection = TcpStream::connect(&socket);
19
20    let result = tokio::time::timeout(timeout, connection).await;
21
22    match result {
23        Ok(inner_result) => {
24            match inner_result {
25                Ok(_) => true,
26                Err(_) => false,
27            }
28        }
29        Err(_) => false,
30    }
31}
32
33
34pub async fn scan(ip: &str, port_x: u16, port_y: u16) -> ScanResult{
35    let d_ip: IpAddr = ip.parse().expect("Feil ved parsing");
36    let mut list_ports = vec![];
37
38    let all_ports: Vec<u16> = (port_x..=port_y).collect();
39
40    for chunk in all_ports.chunks(100) {
41        let mut tasks = vec![];
42        for &port in chunk {
43            let ip_clone = d_ip;
44            let task = tokio::spawn(async move {
45                if scan_port(ip_clone, port).await { Some(port) } else { None }
46            });
47            tasks.push(task);
48        }
49        for task in tasks {
50            if let Ok(Some(port)) = task.await {
51                list_ports.push(port);
52            }
53        }
54    }
55
56
57
58
59    list_ports.sort();
60    let return_value = ScanResult {ip: ip.parse().expect("Error parsing ip"), ports: list_ports};
61    return return_value;
62}