Skip to content

Commit 6293af0

Browse files
committed
String+IPv4: A simplified check for IPv4 subnet equality
1 parent 3ce7f81 commit 6293af0

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//
2+
// Cornucopia – (C) Dr. Lauer Information Technology
3+
//
4+
import Foundation
5+
6+
public extension String {
7+
8+
/// A simplified check if this and another string are in the same IPv4 subnet.
9+
func CC_isInSameIPv4SubnetAs(other: String) -> Bool {
10+
11+
if self.hasPrefix("169.254.") && other.hasPrefix("169.254.") {
12+
// Link-local uses /16
13+
let part1 = self.components(separatedBy: ".")[...1].joined(separator: ".")
14+
let part2 = other.components(separatedBy: ".")[...1].joined(separator: ".")
15+
return part1 == part2
16+
} else {
17+
// Assume /24 for everything else
18+
let part1 = self.components(separatedBy: ".")[...2].joined(separator: ".")
19+
let part2 = other.components(separatedBy: ".")[...2].joined(separator: ".")
20+
return part1 == part2
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)