1use std::net::{IpAddr, Ipv6Addr};
2
3pub fn ip_match(ip1: &str, ip2: IpAddr) -> bool {
4 let ip1_processed: IpAddr = match ip1 {
5 "localhost" => Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).into(),
6 _ => match ip1.parse() {
7 Ok(ip_processed) => ip_processed,
8 Err(_) => return false,
9 },
10 };
11
12 ip1_processed == ip2
13}
14
15#[cfg(test)]
16mod tests {
17 use super::*;
18 use std::net::{IpAddr, Ipv6Addr};
19
20 #[test]
21 fn test_ip_match_with_valid_ipv6() {
22 let ip1 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
23 let ip2 = ip1.parse::<IpAddr>().unwrap();
24 assert!(ip_match(ip1, ip2));
25 }
26
27 #[test]
28 fn test_ip_match_with_valid_ipv4() {
29 let ip1 = "192.168.1.1";
30 let ip2 = ip1.parse::<IpAddr>().unwrap();
31 assert!(ip_match(ip1, ip2));
32 }
33
34 #[test]
35 fn test_ip_match_with_localhost() {
36 let ip1 = "localhost";
37 let ip2 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).into();
38 assert!(ip_match(ip1, ip2));
39 }
40
41 #[test]
42 fn test_ip_match_with_invalid_ip() {
43 let ip1 = "invalid_ip";
44 let ip2 = "192.168.1.1".parse::<IpAddr>().unwrap();
45 assert!(!ip_match(ip1, ip2));
46 }
47
48 #[test]
49 fn test_ip_match_with_different_ips() {
50 let ip1 = "192.168.1.1";
51 let ip2 = "192.168.1.2".parse::<IpAddr>().unwrap();
52 assert!(!ip_match(ip1, ip2));
53 }
54
55 #[test]
56 fn test_ip_match_with_empty_string() {
57 let ip1 = "";
58 let ip2 = "192.168.1.1".parse::<IpAddr>().unwrap();
59 assert!(!ip_match(ip1, ip2));
60 }
61
62 #[test]
63 fn test_ip_match_with_localhost_and_different_ip() {
64 let ip1 = "localhost";
65 let ip2 = "192.168.1.1".parse::<IpAddr>().unwrap();
66 assert!(!ip_match(ip1, ip2));
67 }
68}