ironRoei
ironRoei

Reputation: 2209

iOS - Check if mask ip is in valid(in range of the ip)

So i am trying to figure out how to validate the mask ip(in range?) according to the ip. I cant seem to find the tools in swift as in java :

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

Upvotes: 0

Views: 643

Answers (1)

Serhii Didanov
Serhii Didanov

Reputation: 2348

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

Upvotes: 1

Related Questions