aboutsummaryrefslogtreecommitdiff
path: root/minecraft-client/src/ping.rs
blob: a7a0178656a62432a13c58275b8ea8018140e53c (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
///! Ping Minecraft servers.
use minecraft_protocol::{
    connect::Connection,
    packets::{
        handshake::client_intention_packet::ClientIntentionPacket,
        status::{
            clientbound_status_response_packet::ClientboundStatusResponsePacket,
            serverbound_status_request_packet::ServerboundStatusRequestPacket,
        },
        ConnectionProtocol, Packet, PacketTrait, PROTOCOL_VERSION,
    },
    resolver, ServerAddress,
};

pub async fn ping_server(
    address: &ServerAddress,
) -> Result<ClientboundStatusResponsePacket, String> {
    let resolved_address = resolver::resolve_address(address).await?;

    let mut conn = Connection::new(&resolved_address).await?;

    // send the client intention packet and switch to the status state
    conn.send_packet(
        ClientIntentionPacket {
            protocol_version: PROTOCOL_VERSION,
            hostname: address.host.clone(),
            port: address.port,
            intention: ConnectionProtocol::Status,
        }
        .get(),
    )
    .await;
    conn.switch_state(ConnectionProtocol::Status);

    // send the empty status request packet
    conn.send_packet(ServerboundStatusRequestPacket {}.get())
        .await;

    let packet = conn.read_packet().await.unwrap();

    Ok(match packet {
        Packet::ClientboundStatusResponsePacket(p) => p,
        _ => Err("Invalid packet type".to_string())?,
    })
}