import java.util.*;
public class Solution {
/**
* 验证IP地址
* @param IP string字符串 一个IP地址字符串
* @return string字符串
*/
public String solve (String IP) {
// write code here
if (IP == null || IP.length() < 1) {
return "Neither";
}
char[] chars = IP.toCharArray();
//1.先判断是 v4还是v6
boolean isV4Type = false;
for (char item : chars) {
if (item == '.') {
isV4Type = true;
break;
} else if (item == ':') {
isV4Type = false;
break;
}
}
return isV4Type ? (isV4Validate(IP) ? "IPv4" : "Neither")
: (isV6Valiedate(IP) ? "IPv6" : "Neither" );
}
private boolean isV4Validate(String ip) {
String[] data = ip.split("\\.");
if (data.length != 4) {
return false;
}
for (String item : data) {
if (item.length() > 1 && item.startsWith("0")) {
return false;
}
try {
int value = Integer.valueOf(item);
if (value < 0 || value > 255) {
return false;
}
} catch (Exception e) {
return false;
}
}
return true;
}
private boolean isV6Valiedate(String ip) {
char[] data = ip.toCharArray();
int count = 0;
for (char item : data) {
if (item == ':') {
if (count > 4 || count == 0) {
//每组有4个数
return false;
}
count = 0;
} else {
if ( !(item >= '0' && item <= '9' )
&& !(item >= 'a' && item <= 'f')
&& !(item >= 'A' && item <= 'F')) {
return false;
} else {
count ++;
}
}
}
if(count == 0){
//1db8:85a3:0:0:8A2E:0370:7334:
return false;
}
return true;
}
}