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 v4Type = false;
for(char item : chars){
if(item == '.'){
v4Type = true;
break;
}else if(item ==':'){
v4Type = false;
break;
}
}
return v4Type ?
(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 val = Integer.parseInt(item);
if(!(val >=0 && val <= 255)){
return false;
}
}catch(NumberFormatException 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){
return false;
}
count = 0;
}else if( !( (item >= '0' && item <= '9') || (item>='a' && item <= 'f') || (item >= 'A' && item <= 'F') )){
return false;
}else{
count ++;
}
}
return true;
}
}