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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package com.capgemini.basics;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class Main {
private static Pattern VALID_IPV4_PATTERN = null;
private static Pattern VALID_IPV6_PATTERN1 = null;
private static Pattern VALID_IPV6_PATTERN2 = null;
private static final String ipv4Pattern ="(([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])\\\\.){3}([01]?\\\\d\\\\d?|2[0-4]\\\\d|25[0-5])";
private static final String ipv6Pattern1 ="([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";
private static final String ipv6Pattern2 ="^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$";
static {
try {
VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
VALID_IPV6_PATTERN1 = Pattern.compile(ipv6Pattern1, Pattern.CASE_INSENSITIVE);
VALID_IPV6_PATTERN2 = Pattern.compile(ipv6Pattern2, Pattern.CASE_INSENSITIVE);
} catch (PatternSyntaxException e) {
System.out.println("Neither");
}
}
public static List<String> validateAddresses(List<String> ipAddress) {
final List<String> validity= new ArrayList<String>();
int len = ipAddress.size();
for(int i=0; i<len; i++){
Matcher m1 = Main.VALID_IPV4_PATTERN.matcher(ipAddress.get(i));
Matcher m12 = Main.VALID_IPV6_PATTERN1.matcher(ipAddress.get(i));
Matcher m22 = Main.VALID_IPV6_PATTERN2.matcher(ipAddress.get(i));
if (m1.matches()) {
validity.add("IPv4");
}
else if(m12.matches() || m22.matches()){
validity.add("IPv6");
}
else{
validity.add("Neither");
}
}
return validity;
}
public static void main(String[] args)
{
final List<String> IPAddress = new ArrayList<String>();
//Test Case 0
/*IPAddress.add("121.18.19.20");
IPAddress.add("0.12.12.34");
IPAddress.add("121.234.12.12");
IPAddress.add("23.45.12.56");
IPAddress.add("0.1.2.3");*/
//Test Case 1
/*IPAddress.add("2001:0db8:0000:0000:0000:ff00:0042:8329");
IPAddress.add("2001:0db8:0:0:0:ff00:42:8329");
IPAddress.add("::1");
IPAddress.add("2001:0db8::ff00:42:8329");
IPAddress.add("0000:0000:0000:0000:0000:0000:0000:0001");*/
//Test Case 2
/*IPAddress.add("000.012.234.23");
IPAddress.add("666.666.23.23");
IPAddress.add(".213.123.23.32");
IPAddress.add("23.45.22.32.");
IPAddress.add("272:2624:235e:3bc2:c46d:682:5d46:638g");
IPAddress.add("1:22:333:4444");*/
final List<String> result = validateAddresses(IPAddress);
for (int i=0; i<result.size(); i++)
System.out.println(result.get(i)+"");
}
} |