Java examples for java.util.regex:Match IP Address
is Valid External IP Address by regex
//package com.java2s; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] argv) throws Exception { String address = "java2s.com"; System.out.println(isValidExternalAddress(address)); }//from w ww.ja v a 2 s . co m public static final Pattern IPV4_PATTERN = Pattern .compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"); public static boolean isValidExternalAddress(String address) { try { int[] octets = parseIpv4Address(address); return isValidExternalAddress(octets); } catch (RuntimeException ex) { return false; } } private static boolean isValidExternalAddress(int[] octets) { return isValidAddress(octets) && !isLoopBackAddress(octets) && !isIanaReservedPrivateNetworkAddress(octets); } public static int[] parseIpv4Address(String address) { Matcher m = IPV4_PATTERN.matcher(address); if (!m.find()) { throw new RuntimeException("Invalid IP address: " + address); } int[] octets = new int[4]; octets[0] = Integer.parseInt(m.group(1)); octets[1] = Integer.parseInt(m.group(2)); octets[2] = Integer.parseInt(m.group(3)); octets[3] = Integer.parseInt(m.group(4)); return octets; } public static boolean isValidAddress(String address) { try { int[] octets = parseIpv4Address(address); return isValidAddress(octets); } catch (RuntimeException ex) { return false; } } public static boolean isValidAddress(int[] octets) { return !(octets[0] == 0 && octets[1] == 0 && octets[2] == 0 && octets[3] == 0); } public static boolean isLoopBackAddress(String address) { return isLoopBackAddress(parseIpv4Address(address)); } private static boolean isLoopBackAddress(int[] octets) { return octets[0] == 127 && octets[1] == 0 && octets[2] == 0 && octets[3] == 1; } public static boolean isIanaReservedPrivateNetworkAddress(String address) { return isIanaReservedPrivateNetworkAddress(parseIpv4Address(address)); } private static boolean isIanaReservedPrivateNetworkAddress(int[] octets) { return (octets[0] == 10) || (octets[0] == 172 && octets[1] >= 16 && octets[1] < 32) || (octets[0] == 192 && octets[1] == 168); } }