-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay_16_ValidateIPAddress.java
46 lines (40 loc) · 1.18 KB
/
Day_16_ValidateIPAddress.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public static String validIPAddress(String IP) {
String[] ipv4 = IP.split("\\.",-1);
String[] ipv6 = IP.split("\\:",-1);
if(ipv4.length==4){
for(String s : ipv4) {
if(isIPv4(s)) continue;
else return "Neither";
}
return "IPv4";
}
if(ipv6.length==8){
for(String s : ipv6) {
if(isIPv6(s)) continue;
else return "Neither";
}
return "IPv6";
}
return "Neither";
}
public static boolean isIPv4 (String s){
try{
return String.valueOf(Integer.valueOf(s)).equals(s) &&
Integer.parseInt(s) >= 0 &&
Integer.parseInt(s) <= 255;
}
catch (NumberFormatException e){
return false;
}
}
public static boolean isIPv6 (String s){
if (s.length() > 4 ) return false;
try {
return Integer.parseInt(s, 16) >= 0 && s.charAt(0)!='-';
}
catch (NumberFormatException e){
return false;
}
}
}