Skip to main content

minecraft_java_rs_core/net/
check.rs

1use std::time::Duration;
2
3/// Returns `true` if an outgoing HTTP connection can be established.
4///
5/// Makes a GET request to Google's generate_204 endpoint (returns 204 No
6/// Content instantly, so there's no body to parse and the round-trip is fast).
7/// Falls back to `false` on any error including timeout.
8pub async fn check_internet() -> bool {
9    let client = match reqwest::Client::builder()
10        .timeout(Duration::from_secs(5))
11        .build()
12    {
13        Ok(c) => c,
14        Err(_) => return false,
15    };
16
17    client
18        .get("https://connectivitycheck.gstatic.com/generate_204")
19        .send()
20        .await
21        .is_ok()
22}
23
24// ── Tests ─────────────────────────────────────────────────────────────────────
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[tokio::test]
31    async fn unreachable_host_returns_false() {
32        // A syntactically valid but unreachable URL: should return false quickly.
33        let client = reqwest::Client::builder()
34            .timeout(Duration::from_millis(200))
35            .build()
36            .unwrap();
37        let result = client
38            .get("http://192.0.2.1/generate_204") // TEST-NET-1, RFC 5737
39            .send()
40            .await;
41        assert!(result.is_err());
42    }
43}