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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! # CanIHazIP
//! CanIHazIP gets your current public ip address using https://canihazip.com
//!
//! # Example
//! ```rust
//! extern crate canihazip;
//! # use std::net::Ipv4Addr;
//!
//! # fn main() -> Result<(), reqwest::Error> {
//! let ip = canihazip::plz_ip()?;
//!
//! assert_eq!(ip.is_loopback(), false);
//! # Ok(())
//! # }
//! ```
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

/// Get your current public IP address.
///
/// Panics if the returned IP is not a valid IP address.
pub fn plz_ip() -> Result<IpAddr, reqwest::Error> {
    Ok(reqwest::blocking::get("https://icanhazip.com/")?
        .text()?
        .trim()
        .parse::<IpAddr>()
        .expect("Error parsing IP address"))
}

/// Get your current public IPv4 address.
///
/// Panics if the returned IP is not a valid IPv4 address.
pub fn plz_ipv4() -> Result<Ipv4Addr, reqwest::Error> {
    Ok(reqwest::blocking::get("https://4.icanhazip.com/")?
        .text()?
        .trim()
        .parse::<Ipv4Addr>()
        .expect("Error parsing IPv4 address"))
}

/// Get your current public IPv6 address.
///
/// Errors if there is no Ipv6 connectivity.
/// Panics if the returned IP is not a valid IPv6 address.
pub fn plz_ipv6() -> Result<Ipv6Addr, reqwest::Error> {
    Ok(reqwest::blocking::get("https://6.icanhazip.com/")?
        .text()?
        .trim()
        .parse::<Ipv6Addr>()
        .expect("Error parsing IPv6 address"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_plz_ip() {
        let ip = plz_ip().unwrap();

        assert_eq!(ip.is_loopback(), false);
        assert_eq!(ip.is_unspecified(), false);
    }

    #[test]
    fn test_plz_ipv4() {
        let ip = plz_ipv4().unwrap();

        assert_eq!(ip.is_private(), false);
        assert_eq!(ip.is_loopback(), false);
        assert_eq!(ip.is_link_local(), false);
        assert_eq!(ip.is_broadcast(), false);
        assert_eq!(ip.is_documentation(), false);
        assert_eq!(ip.is_unspecified(), false);
    }

    #[test]
    #[ignore]
    fn test_plz_ipv6() {
        let ip = plz_ipv6().unwrap();

        assert_eq!(ip.is_loopback(), false);
        assert_eq!(ip.is_unspecified(), false);
        assert_eq!(ip.is_multicast(), false);
    }
}