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 :
Asked
Active
Viewed 562 times
1 Answers
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

Serhii Didanov
- 2,200
- 1
- 16
- 31
-
what is the "pref" stands for? – ironRoei Sep 12 '18 at 07:03
-
pref is prefix netmask. I mean 192.168.1.0/24. 24 is prefix – Serhii Didanov Sep 12 '18 at 09:12
-
What is usually the default? – ironRoei Sep 12 '18 at 09:13
-
No "usually the default". Each IP-address may use different prefix. 192.168.1.1 may have prefix from /1 to /31. Prefix depends on network configuration – Serhii Didanov Sep 12 '18 at 09:16
-
so what i need more from my backend team?(to get in json) – ironRoei Sep 12 '18 at 10:06
-
You need: 1) IP-address (that you want to check: "192.168.1.1"), 2) IP-network ( IP-address must belong to "192.168.1.0"), 3) Prefix of IP-network ("24") – Serhii Didanov Sep 12 '18 at 11:54
-
Also I suggest you to read more about this: https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing – Serhii Didanov Sep 12 '18 at 11:55
-
Thanks a lot!! very helpful answer – ironRoei Sep 12 '18 at 13:26
-
Hi, do you know how to calculate the prefix from the mask? as i told i need to calculate it from that, for example 255 is 8 bites that is why 255.255.255.0 is 24 – ironRoei Oct 08 '18 at 17:26
-
I have managed to resolve that, do you want me to open any how? – ironRoei Oct 09 '18 at 09:14
-
@SergeyDidanov are you sure the calculation works as it should be? for net 192.168.2.0/22 and ip 192.168.1.0 the above code returns false when it should be true. – prabhu Nov 24 '22 at 08:10