-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-16 Validate IP Address
57 lines (51 loc) · 1.58 KB
/
Day-16 Validate IP Address
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
47
48
49
50
51
52
53
54
55
56
class Solution {
public String validIPAddress(String IP) {
String ipv4set="([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])";
String ipv4regex="^("+ipv4set+"\\.){3}"+ipv4set+"$";
String ipv6set="([0-9a-fA-F]{1,4})";
String ipv6regex="("+ipv6set+"\\:){7}"+ipv6set;
if( IP.matches(ipv4regex) ){
return "IPv4";
}
else if(IP.matches(ipv6regex)){
return "IPv6";
}
else{
return "Neither";
}
}
}
class Solution {
public String validateIPv4(String IP) {
String[] nums = IP.split("\\.", -1);
for (String x : nums) {
if (x.length() == 0 || x.length() > 3) return "Neither";
if (x.charAt(0) == '0' && x.length() != 1) return "Neither";
for (char ch : x.toCharArray()) {
if (! Character.isDigit(ch)) return "Neither";
}
if (Integer.parseInt(x) > 255) return "Neither";
}
return "IPv4";
}
public String validateIPv6(String IP) {
String[] nums = IP.split(":", -1);
String hexdigits = "0123456789abcdefABCDEF";
for (String x : nums) {
if (x.length() == 0 || x.length() > 4) return "Neither";
for (Character ch : x.toCharArray()) {
if (hexdigits.indexOf(ch) == -1) return "Neither";
}
}
return "IPv6";
}
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";
}
}