描述 编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址
IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(“.”)分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (“:”)分割。比如,
2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 ( : : ) 的情况。 比如,2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。 同时,在 IPv6 地址中,多余的 0也是不被允许的。比如,02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
说明: 你可以认为给定的字符串里没有空格或者其他特殊字符。
采用分隔字符串,逐个合法性检测的方法处理IP地址字符串
swift:
func solveIPAdress ( _ IP: String) -> String {
if IP.count <= 0 {
return "Neither" }
if check_IPv4_usingSplit(IP) {
return "IPv4"
}else if check_IPv6_usingSplit(IP) {
return "IPv6"
}else{
return "Neither"
}
}
func check_IPv4_usingSplit ( _ IP: String) -> Bool {
let adress = IP.components(separatedBy: ".")
if adress.count != 4 {
return false //ip地址不满足数量四
}
for i in 0..<adress.count {
if adress[i].count <= 0 || adress[i].count > 3 {
return false //ip地址位数 不合法
}
let strAray = Array(adress[i])
let firstNum = strAray[0] //ip地址首位数字
if firstNum == "0" && adress[i].count > 1 {
return false //存在前导0
}
for str in strAray {
if ((Character(String(str)).asciiValue! >= Character("a").asciiValue! &&
Character(String(str)).asciiValue! <= Character("z").asciiValue!) ||
(Character(String(str)).asciiValue! >= Character("A").asciiValue! &&
Character(String(str)).asciiValue! <= Character("Z").asciiValue!)) {
return false //ipv4地址中没有 a-z A-Z
}
}
var num = 0
for str in strAray {
num = num * 10 + Int(Character(String(str)).asciiValue! - Character("0").asciiValue!)
}
if num < 0 || num > 255 {
return false //ip地址大小不合法
}
}
return true
}
func check_IPv6_usingSplit ( _ IP: String) -> Bool {
let adress = IP.components(separatedBy: ":")
if adress.count != 8 {
return false //ipv6位数不满足8位
}
for i in 0..<adress.count {
if adress[i].count <= 0 || adress[i].count > 4 {
return false //ipv6地址位 1-4
}
let strArray = Array(adress[i])
for str in strArray {
if !((Character(String(str)).asciiValue! >= Character("a").asciiValue! &&
Character(String(str)).asciiValue! <= Character("f").asciiValue!) ||
(Character(String(str)).asciiValue! >= Character("A").asciiValue! &&
Character(String(str)).asciiValue! <= Character("F").asciiValue!) ||
(Character(String(str)).asciiValue! >= Character("0").asciiValue! &&
Character(String(str)).asciiValue! <= Character("9").asciiValue!)) {
return false //ipv4地址只有 0-9 a-z A-Z
}
}
}
return true
}