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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// This library lets you get computer and network information easily. It lets
// you get your public IP address and stuff like that. See the examples folder.

use std::process::Command;

pub struct New;

impl New {
    // Return hostname
    pub fn hostname(&self) -> String {
        let cmd = Command::new("hostname")
            .output()
            .expect("Failed to retrieve hostname");
        let cmd_str = String::from_utf8(cmd.stdout).unwrap();
        cmd_str.replace("\n", "")
    }

    // Return public IP address
    pub fn pub_ip(&self) -> String {
        if cfg!(unix) {
            let cmd = Command::new("curl")
                .arg("-s")
                .arg("https://ipinfo.io/ip")
                .output()
                .expect("Failed to retrieve public IP");
            let cmd_str = String::from_utf8(cmd.stdout).unwrap();

            // If the command output is not empty, then return the IP. But
            // if it's empty, chances are that the user is not connected to
            // the internet because the curl command doesn't output anything
            // when you are not connected to the internet.
            if cmd_str != "" {
                cmd_str
            } else {
                String::from("Check network connectivity")
            }
        } else {
            String::from("Unknown public IP")
        }
    }

    // Ping a website and return the connectivity result
    pub fn ping(&self, url: &str) -> bool {
        if cfg!(unix) {
            let cmd = Command::new("ping")
                .arg("-c")
                .arg("1")
                .arg(url)
                .output()
                .expect("Connectivity failed");
            let cmd_str = String::from_utf8(cmd.stdout).unwrap();

            // If the command output is not empty, then return the result.
            // But if it's empty, chances are that the user is not connected
            // to the internet because the ping command fails when you are not
            // connected to the internet.
            if cmd_str != "" {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}