Searching...
Friday, 10 May 2013

IPV6 Java Regular expression example

11:00

Pattern

private static final Pattern IPV6REGEX = Pattern.compile(""
+ "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}"
+ "|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]"
+ "|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,"
+ "4})(?<![^:]:|\\.)\\z", Pattern.CASE_INSENSITIVE);

Example

package com.pretech;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

public class Ipv6Example {
private static final Pattern IPV6REGEX = Pattern.compile(
"" + "^(((?=(?>.*?::)(?!.*::)))(::)?([0-9A-F]{1,4}::?){0,5}"
+ "|([0-9A-F]{1,4}:){6})(\\2([0-9A-F]{1,4}(::?|$)){0,2}|((25[0-5]"
+ "|(2[0-4]|1\\d|[1-9])?\\d)(\\.|$)){4}|[0-9A-F]{1,4}:[0-9A-F]{1,"
+ "4})(?<![^:]:|\\.)\\z",
Pattern.CASE_INSENSITIVE);

public static void main(String[] args) {

URL url;
int i1, i2;

try {
url = new URL("http://[FF01:0:0:0:0:0:0:0101]");
String originalHostName = url.getHost();

System.out.println(originalHostName);
if (originalHostName.startsWith("[") && originalHostName.endsWith("]")) {

i1 = originalHostName.indexOf("[");

originalHostName = originalHostName.substring(i1 + 1);

i2 = originalHostName.lastIndexOf("]");

originalHostName = originalHostName.substring(0, i2);

if (IPV6REGEX.matcher(originalHostName).matches()) {

System.out.println(url + " is a ipv6 address");
String hostName = InetAddress.getByName(originalHostName).getHostAddress().toLowerCase();
if (hostName.contains(":")) {
hostName = "[" + hostName + "]";
}

}
}

} catch (MalformedURLException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Output

[FF01:0:0:0:0:0:0:0101]
http://[FF01:0:0:0:0:0:0:0101] is a ipv6 address

0 comments: