dator/
ip.rs

1use std::net::Ipv6Addr;
2
3/// Checks whether the given string is a valid IPv4 address.
4///
5/// # Example
6///
7///
8/// ```
9/// if dator::ipv4("0.0.0.0") {
10///     // 0.0.0.0 is a valid IPv4
11/// }
12/// ```
13///
14/// ```
15/// if !dator::ipv4("fe80::") {
16///     // fe80:: is an invalid IPv4
17/// }
18/// ```
19pub fn ipv4(ip: &str) -> bool {
20    // IP string size is 7 <= ip.len() <= 15
21    if ip.len() < 7 || ip.len() > 15 {
22        return false;
23    }
24
25    // Number of parts
26    let mut n_parts: u8 = 0;
27
28    for part in ip.split('.') {
29        //print!("part[{}]={}", n_dots, part);
30
31        if let Err(_) = str::parse::<u8>(part) {
32            return false;
33        }
34
35        // Stop the check, ip is 100% invalid
36        if n_parts > 4 {
37            return false;
38        }
39
40        n_parts += 1;
41    }
42
43    n_parts == 4
44}
45
46/// Checks whether the given string is a valid IPv6 address.
47///
48/// # Example
49///
50///
51/// ```
52/// if dator::ipv6("fe80::") {
53///     // "fe80::" is a valid IPv6
54/// }
55/// ```
56///
57/// ```
58/// if !dator::ipv6("1.1.1.1") {
59///     // 1.1.1.1 is an invalid IPv6
60/// }
61/// ```
62pub fn ipv6(ip: &str) -> bool {
63    if ip.len() < 2 || ip.len() > 39 || !ip.contains(':') {
64        return false;
65    }
66
67    ip.parse::<Ipv6Addr>().is_ok()
68}
69
70/// Checks whether the given string is a valid IP address.
71///
72/// Both IPv4 and IPv6 returned as valid.
73///
74/// # Example
75///
76/// ```
77/// if dator::ip("1.1.1.1") {
78///     // 1.1.1.1 is a valid IP
79/// }
80/// ```
81/// ```
82/// if dator::ip("fe80::") {
83///     // "fe80::" is a valid IP
84/// }
85/// ```
86/// ```
87/// if !dator::ip("example.com") {
88///     // example.com is not a valid IP
89/// }
90/// ```
91pub fn ip(ip: &str) -> bool {
92    ipv4(ip) || ipv6(ip)
93}