public String validIPAddress(String IP) {
if (IP.chars().filter(ch -> ch == '.').count() == 3) {
return validateIPv4(IP);
}
else if (IP.chars().filter(ch -> ch == ':').count() == 7) {
return validateIPv6(IP);
}
else {
return "Neither";
}
}
private String validateIPv4(String ip) {
String[] strs = ip.split("\\.", -1); // 保留空字符串
for (String str : strs) {
if (str.length() == 0 || str.length() > 3) return "Neither";
if (str.charAt(0) == '0' && str.length() != 1) return "Neither";
for (char ch : str.toCharArray()) {
if (!Character.isDigit(ch)) return "Neither";
}
if (Integer.parseInt(str) > 255) return "Neither";
}
return "IPv4";
}
private String validateIPv6(String ip) {
String[] strs = ip.split(":", -1);
String hexdigits = "0123456789abcdefABCDEF";
for (String str : strs) {
if (str.length() == 0 || str.length() > 4) return "Neither";
for (char ch : str.toCharArray()) {
if (hexdigits.indexOf(ch) == -1) return "Neither";
}
}
return "IPv6";
}
468. 验证IP地址
最新推荐文章于 2023-07-04 16:52:59 发布