aboutsummaryrefslogtreecommitdiff
path: root/minecraft-protocol/src/lib.rs
blob: aaf3da509548aee09e5ec7628bd940a941289ec3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//! This lib is responsible for parsing Minecraft packets.

use std::net::IpAddr;
use std::str::FromStr;

pub mod connection;
pub mod mc_buf;
pub mod packets;
pub mod resolver;
pub mod server_status_pinger;

#[derive(Debug)]
pub struct ServerAddress {
    pub host: String,
    pub port: u16,
}

#[derive(Debug)]
pub struct ServerIpAddress {
    pub ip: IpAddr,
    pub port: u16,
}

impl ServerAddress {
    /// Convert a Minecraft server address (host:port, the port is optional) to a ServerAddress
    pub fn parse(string: &str) -> Result<ServerAddress, String> {
        if string.is_empty() {
            return Err("Empty string".to_string());
        }
        let mut parts = string.split(':');
        let host = parts.next().ok_or("No host specified")?.to_string();
        // default the port to 25565
        let port = parts.next().unwrap_or("25565");
        let port = u16::from_str(port).map_err(|_| "Invalid port specified")?;
        Ok(ServerAddress { host, port })
    }
}

pub async fn connect(address: ServerAddress) -> Result<(), Box<dyn std::error::Error>> {
    let resolved_address = resolver::resolve_address(&address).await;
    println!("Resolved address: {:?}", resolved_address);
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}