Reputation: 844
IPv4 addresses are relatively easy to validate: they have 4 octets, separated by digits. Each octet is an integer ranging from 0-255.
IPv6 addresses are difficult to validate. They have 8 hextets, each with 4 hexadecimal digits, separated by colons. IPv6 addresses also have shortening rules where leading zeros in each hextet can be removed (leaving at least one zero in each hextet). Additionally one or more consecutive :0: hextets can be shortened to ::, but only once in each IPv6 address.
How can I validate IPv4 and IPv6 addresses in Swift?
Upvotes: 3
Views: 1752
Reputation: 844
The Network framework has a failable initializer for the structs IPv4Address and IPv6Address which take a String constructor. Simply testing to see if the Struct can be initialized with the string is sufficient to validate the address.
This is particularly useful for IPv6 addresses which have a long format with non-trivial shortening rules.
import Network
let addresses = ["1.2.33.44","1.265.33.33","2001:db8::35:44","2001:db8::33::44"]
for address in addresses {
if let _ = IPv4Address(address) {
print("address \(address) is a valid IPv4 address")
} else if let _ = IPv6Address(address) {
print("address \(address) is a valid IPv6 address")
} else {
print("address \(address) is neither an IPv4 address nor an IPv6 address")
}
}
output:
address 1.2.33.44 is a valid IPv4 address
address 1.265.33.33 is neither an IPv4 address nor an IPv6 address
address 2001:db8::35:44 is a valid IPv6 address
address 2001:db8::33::44 is neither an IPv4 address nor an IPv6 address
Upvotes: 5