Validate IP Address
Input: "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".Last updated
Input: "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".Last updated
Input: "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address.class Solution {
public String validIPAddress(String IP) {
if(IP == null || IP.length() == 0)
return "Neither";
if(IP.charAt(0) == '.' ||IP.charAt(0) == ':' || IP.charAt(IP.length()-1) == '.' ||IP.charAt(IP.length()-1) == ':')
return "Neither";
if(IP.indexOf(".") != -1){
String[] sArray = IP.split("\\.");
System.out.println("sArray "+IP.indexOf("."));
return checkIPv4(sArray);
}
else if(IP.indexOf(":") != -1){
String[] sArray = IP.split(":");
return checkIPv6(sArray);
}else{
return "Neither";
}
}
public String checkIPv4(String[] ip){
if(ip.length != 4)
return "Neither";
for(int i =0; i < ip.length; i++){
String subIp = ip[i];
System.out.println(subIp);
//开头不能为0;
if( subIp == null || subIp.length() == 0 ||(subIp.charAt(0) =='0' && subIp.length() > 1))
return "Neither";
if(subIp.length() > 4)
return "Neither";
for(int j = 0; j < subIp.length();j++){
if(subIp.charAt(j) >='0' && subIp.charAt(j) <='9')
continue;
else
return "Neither";
}
int nums = Integer.parseInt(subIp);
if(nums< 0 || nums > 255)
return "Neither";
}
return "IPv4";
}
public String checkIPv6(String[] ip){
System.out.println("啊啊啊 "+ip.length);
if(ip.length != 8)
return "Neither";
for(int i =0; i < ip.length;i++){
String subIP = ip[i];
if(subIP == null || subIP.length() == 0 || subIP.length() > 4)
return "Neither";
for(int j = 0; j < subIP.length() ;j++){
if((subIP.charAt(j)>= '0' && subIP.charAt(j) <= '9' ) || (subIP.charAt(j)>= 'a' && subIP.charAt(j) <= 'f') || (subIP.charAt(j)>= 'A' && subIP.charAt(j) <= 'F')){
continue;
}
else{
return "Neither";
}
}
}
return "IPv6";
}
}