VPN: Cleaner derivation of subnet mask from CIDR network prefix length

This commit is contained in:
Roopesh Chander 2018-10-28 11:51:18 +05:30
parent 5add29a5c8
commit 2781026728
1 changed files with 8 additions and 14 deletions

View File

@ -155,21 +155,15 @@ class PacketTunnelOptionsGenerator {
} }
static func ipv4SubnetMaskString(of addressRange: IPAddressRange) -> String { static func ipv4SubnetMaskString(of addressRange: IPAddressRange) -> String {
var n: UInt8 = addressRange.networkPrefixLength let n: UInt8 = addressRange.networkPrefixLength
assert(n <= 32) assert(n <= 32)
var components: [UInt8] = [] var octets: [UInt8] = [0, 0, 0, 0]
while (n >= 8) { let subnetMask: UInt32 = n > 0 ? ~UInt32(0) << (32 - n) : UInt32(0)
components.append(255) octets[0] = UInt8(truncatingIfNeeded: subnetMask >> 24)
n = n - 8 octets[1] = UInt8(truncatingIfNeeded: subnetMask >> 16)
} octets[2] = UInt8(truncatingIfNeeded: subnetMask >> 8)
if (n > 0) { octets[3] = UInt8(truncatingIfNeeded: subnetMask)
components.append(((1 << n) - 1) << (8 - n)) return octets.map { String($0) }.joined(separator: ".")
}
while (components.count < 4) {
components.append(0)
}
assert(components.count == 4)
return components.map { String($0) }.joined(separator: ".")
} }
} }