iOS - 检查掩码ip是否有效(在ip范围内)

问题描述 投票:0回答:1

所以我想弄清楚如何根据ip验证掩码ip(在范围内?)。我似乎无法像在java中那样在swift中找到工具:

How can I detect if an IP is in a network?

ios swift ip mask
1个回答
1
投票
let ip = "192.168.2.0"
let net = "192.168.1.0"
let pref = 24

func convertIpToInt(_ ipAddress: String) -> Int? {
   var result = 0.0
   let ipAddressArray = ipAddress.components(separatedBy: ".").compactMap { 
      Double($0) }
   guard ipAddressArray.count == 4 else { return nil }
   for (index, element) in ipAddressArray.enumerated() {
      result += element * pow(256, Double(3 - index))
   }

   return Int(result) > 0 ? Int(result) : nil
}

let ipInt = convertIpToInt(ip)
let netInt = convertIpToInt(net)
let brkstInt = netInt! + Int(pow(2, Double(32-pref))) - 1


print(ipInt! >= netInt! && ipInt! <= brkstInt) // false
© www.soinside.com 2019 - 2024. All rights reserved.