1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00
azalea/azalea-client/src/ping.rs
mat 7b3e2e4bf7
1.20.2 (#99)
* add configuration state

* start updating to 23w31a

* implement a bit more of 23w31a

* chunk batching

* start adding configuration state

* ioasfhjgsd

* almost works

* configuration state mostly implemented

* handle other packets in configuration state and fix keepalive

* cleanup, fix warnings

* 23w32a

* fix some doctests

* 23w33a

* 23w35a

* 1.20.2-pre2

* fix system conflicts

* 1.20.2-pre4

* make tests compile

* tests pass

* 1.20.2-rc2

* 1.20.2

* Revert "1.20.2"

This reverts commit dd152fd265.

* didn't mean to commit that code

---------

Co-authored-by: mat <git@matdoes.dev>
2023-09-21 11:16:29 -05:00

81 lines
2.3 KiB
Rust
Executable file

//! Ping Minecraft servers.
use azalea_protocol::{
connect::{Connection, ConnectionError},
packets::{
handshaking::client_intention_packet::ClientIntentionPacket,
status::{
clientbound_status_response_packet::ClientboundStatusResponsePacket,
serverbound_status_request_packet::ServerboundStatusRequestPacket,
ClientboundStatusPacket,
},
ConnectionProtocol, PROTOCOL_VERSION,
},
resolver, ServerAddress,
};
use std::io;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum PingError {
#[error("{0}")]
Resolver(#[from] resolver::ResolverError),
#[error("{0}")]
Connection(#[from] ConnectionError),
#[error("{0}")]
ReadPacket(#[from] Box<azalea_protocol::read::ReadPacketError>),
#[error("{0}")]
WritePacket(#[from] io::Error),
#[error("The given address could not be parsed into a ServerAddress")]
InvalidAddress,
}
/// Ping a Minecraft server.
///
/// # Examples
///
/// ```rust,no_run
/// use azalea_client::ping;
///
/// #[tokio::main]
/// async fn main() {
/// let response = ping::ping_server("play.hypixel.net").await.unwrap();
/// println!("{}", response.description.to_ansi());
/// }
/// ```
pub async fn ping_server(
address: impl TryInto<ServerAddress>,
) -> Result<ClientboundStatusResponsePacket, PingError> {
let address: ServerAddress = address.try_into().map_err(|_| PingError::InvalidAddress)?;
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.write(
ClientIntentionPacket {
protocol_version: PROTOCOL_VERSION,
hostname: address.host.clone(),
port: address.port,
intention: ConnectionProtocol::Status,
}
.get(),
)
.await?;
let mut conn = conn.status();
// send the empty status request packet
conn.write(ServerboundStatusRequestPacket {}.get()).await?;
let packet = conn.read().await?;
loop {
match packet {
ClientboundStatusPacket::StatusResponse(p) => return Ok(p),
ClientboundStatusPacket::PongResponse(_) => {
// we should never get this packet since we didn't send a ping
}
}
}
}