2018-10-24 01:37:28 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
2018-10-30 02:57:35 +00:00
|
|
|
// Copyright © 2018 WireGuard LLC. All Rights Reserved.
|
2018-10-13 13:29:42 +00:00
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import Network
|
|
|
|
|
|
|
|
struct IPAddressRange {
|
|
|
|
let address: IPAddress
|
|
|
|
var networkPrefixLength: UInt8
|
2018-12-21 04:52:45 +00:00
|
|
|
|
|
|
|
init(address: IPAddress, networkPrefixLength: UInt8) {
|
|
|
|
self.address = address
|
|
|
|
self.networkPrefixLength = networkPrefixLength
|
|
|
|
}
|
2018-10-13 13:29:42 +00:00
|
|
|
}
|
|
|
|
|
2018-10-19 03:45:37 +00:00
|
|
|
extension IPAddressRange {
|
2018-12-21 04:52:45 +00:00
|
|
|
var stringRepresentation: String {
|
|
|
|
return "\(address)/\(networkPrefixLength)"
|
|
|
|
}
|
|
|
|
|
2018-10-19 03:45:37 +00:00
|
|
|
init?(from string: String) {
|
2018-12-21 04:52:45 +00:00
|
|
|
guard let parsed = IPAddressRange.parseAddressString(string) else { return nil }
|
|
|
|
address = parsed.0
|
|
|
|
networkPrefixLength = parsed.1
|
|
|
|
}
|
|
|
|
|
|
|
|
private static func parseAddressString(_ string: String) -> (IPAddress, UInt8)? {
|
2018-10-30 08:15:16 +00:00
|
|
|
let endOfIPAddress = string.lastIndex(of: "/") ?? string.endIndex
|
|
|
|
let addressString = String(string[string.startIndex ..< endOfIPAddress])
|
|
|
|
let address: IPAddress
|
2018-10-19 03:45:37 +00:00
|
|
|
if let addr = IPv4Address(addressString) {
|
2018-11-06 17:12:53 +00:00
|
|
|
address = addr
|
2018-10-19 03:45:37 +00:00
|
|
|
} else if let addr = IPv6Address(addressString) {
|
|
|
|
address = addr
|
|
|
|
} else {
|
|
|
|
return nil
|
|
|
|
}
|
2018-12-21 04:52:45 +00:00
|
|
|
|
|
|
|
let maxNetworkPrefixLength: UInt8 = address is IPv4Address ? 32 : 128
|
2018-10-30 08:15:16 +00:00
|
|
|
var networkPrefixLength: UInt8
|
2018-12-12 17:40:57 +00:00
|
|
|
if endOfIPAddress < string.endIndex { // "/" was located
|
2018-10-30 08:15:16 +00:00
|
|
|
let indexOfNetworkPrefixLength = string.index(after: endOfIPAddress)
|
2018-12-12 17:40:57 +00:00
|
|
|
guard indexOfNetworkPrefixLength < string.endIndex else { return nil }
|
2018-10-30 08:15:16 +00:00
|
|
|
let networkPrefixLengthSubstring = string[indexOfNetworkPrefixLength ..< string.endIndex]
|
|
|
|
guard let npl = UInt8(networkPrefixLengthSubstring) else { return nil }
|
|
|
|
networkPrefixLength = min(npl, maxNetworkPrefixLength)
|
2018-10-19 03:45:37 +00:00
|
|
|
} else {
|
2018-10-30 08:15:16 +00:00
|
|
|
networkPrefixLength = maxNetworkPrefixLength
|
2018-10-19 03:45:37 +00:00
|
|
|
}
|
2018-12-21 04:52:45 +00:00
|
|
|
|
|
|
|
return (address, networkPrefixLength)
|
2018-10-19 03:45:37 +00:00
|
|
|
}
|
|
|
|
}
|