net_ssr/
lib.rs

1use std::net::{Ipv4Addr, SocketAddr};
2use std::sync::Arc;
3use tokio::net::UdpSocket;
4use tokio::signal;
5use tokio::sync::Mutex;
6pub mod command;
7
8/// Listen on a specific port and call the provided custom code when a message is received.
9pub async fn listen_on_port<F, Fut>(addr: SocketAddr, custom_code: F, verbose: bool)
10where
11    F: Fn(String, SocketAddr, Arc<Mutex<UdpSocket>>, bool) -> Fut + Send + Sync + 'static,
12    Fut: std::future::Future<Output = ()> + Send,
13{
14    // Bind to the specified address and wrap the socket in an Arc and Mutex for thread-safe access.
15    let socket = Arc::new(Mutex::new(
16        UdpSocket::bind(&addr).await.expect("Failed to bind socket"),
17    ));
18
19    if verbose {
20        println!("Listening on {}", addr);
21    }
22
23    // Buffer for receiving data.
24    let mut buf = vec![0; 1024];
25    loop {
26        // Receive data from any sender and get the length of the message and the sender's address.
27        let (len, addr) = socket
28            .lock()
29            .await
30            .recv_from(&mut buf)
31            .await
32            .expect("Failed to receive data");
33        // Convert the received bytes into an owned string, ignoring non-UTF8 data.
34        let received_string = String::from_utf8_lossy(&buf[..len]).into_owned();
35
36        // Invoke the user-provided custom function with the received data and the cloned socket Arc.
37        custom_code(received_string, addr, Arc::clone(&socket), verbose).await;
38    }
39}
40
41pub fn get_ip_range(start_ip: Ipv4Addr, end_ip: Ipv4Addr) -> Vec<Ipv4Addr> {
42    // Convert the start and end IPv4 addresses to u32
43    let mut current_u32 = ipv4_to_u32(start_ip);
44    let end_u32 = ipv4_to_u32(end_ip);
45
46    let mut ip_list = Vec::new();
47
48    while current_u32 <= end_u32 {
49        // Convert the current u32 to an IPv4 address
50        let ip = u32_to_ipv4(current_u32);
51        ip_list.push(ip);
52        current_u32 += 1;
53    }
54
55    ip_list
56}
57
58/// Convert an IPv4 address to an u32
59fn ipv4_to_u32(ip: Ipv4Addr) -> u32 {
60    let octets = ip.octets();
61    (u32::from(octets[0]) << 24)
62        | (u32::from(octets[1]) << 16)
63        | (u32::from(octets[2]) << 8)
64        | u32::from(octets[3])
65}
66
67/// Convert a u32 to an IPv4 address
68fn u32_to_ipv4(n: u32) -> Ipv4Addr {
69    Ipv4Addr::new(
70        ((n >> 24) & 0xFF) as u8,
71        ((n >> 16) & 0xFF) as u8,
72        ((n >> 8) & 0xFF) as u8,
73        (n & 0xFF) as u8,
74    )
75}
76
77pub fn handle_ctrl_c(verbose: bool) -> tokio::task::JoinHandle<()> {
78    tokio::spawn(async move {
79        signal::ctrl_c().await.expect("Failed to listen for ctrl+c");
80        if verbose {
81            println!("Ctrl+C received!");
82        }
83    })
84}