File size: 1,633 Bytes
9552aa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::net::{IpAddr, Ipv6Addr};

pub fn ip_match(ip1: &str, ip2: IpAddr) -> bool {
  let ip1_processed: IpAddr = match ip1 {
    "localhost" => Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).into(),
    _ => match ip1.parse() {
      Ok(ip_processed) => ip_processed,
      Err(_) => return false,
    },
  };

  ip1_processed == ip2
}

#[cfg(test)]
mod tests {
  use super::*;
  use std::net::{IpAddr, Ipv6Addr};

  #[test]
  fn test_ip_match_with_valid_ipv6() {
    let ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
    let ip2 = ip1.parse::<IpAddr>().unwrap();
    assert!(ip_match(ip1, ip2));
  }

  #[test]
  fn test_ip_match_with_valid_ipv4() {
    let ip1 = "192.168.1.1";
    let ip2 = ip1.parse::<IpAddr>().unwrap();
    assert!(ip_match(ip1, ip2));
  }

  #[test]
  fn test_ip_match_with_localhost() {
    let ip1 = "localhost";
    let ip2 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).into();
    assert!(ip_match(ip1, ip2));
  }

  #[test]
  fn test_ip_match_with_invalid_ip() {
    let ip1 = "invalid_ip";
    let ip2 = "192.168.1.1".parse::<IpAddr>().unwrap();
    assert!(!ip_match(ip1, ip2));
  }

  #[test]
  fn test_ip_match_with_different_ips() {
    let ip1 = "192.168.1.1";
    let ip2 = "192.168.1.2".parse::<IpAddr>().unwrap();
    assert!(!ip_match(ip1, ip2));
  }

  #[test]
  fn test_ip_match_with_empty_string() {
    let ip1 = "";
    let ip2 = "192.168.1.1".parse::<IpAddr>().unwrap();
    assert!(!ip_match(ip1, ip2));
  }

  #[test]
  fn test_ip_match_with_localhost_and_different_ip() {
    let ip1 = "localhost";
    let ip2 = "192.168.1.1".parse::<IpAddr>().unwrap();
    assert!(!ip_match(ip1, ip2));
  }
}