1 19 20 package com.sslexplorer.input.validators; 21 22 import java.net.InetAddress ; 23 import java.net.UnknownHostException ; 24 import java.util.Properties ; 25 import java.util.StringTokenizer ; 26 27 import com.sslexplorer.boot.CodedException; 28 import com.sslexplorer.boot.PropertyDefinition; 29 import com.sslexplorer.core.CoreException; 30 import com.sslexplorer.util.CIDRNetwork; 31 32 36 public class IPAddressValidator extends StringValidator { 37 38 private static final String LOW_RANGE = "0.0.0.0"; 39 private static final String HIGH_RANGE = "255.255.255.255"; 40 41 @Override 42 public void validate(PropertyDefinition definition, String value, Properties properties) throws CodedException { 43 super.validate(definition, value, properties); 44 if (!isIpAddressExpressionValid(value)) { 45 throw new CoreException(ErrorConstants.ERR_STRING_ISNT_IP_ADDRESS, ErrorConstants.CATEGORY_NAME, ErrorConstants.BUNDLE_NAME, null, value); 46 } 47 } 48 49 53 public static boolean isIpAddressExpressionValid(String ipAddress) { 54 if (LOW_RANGE.equals(ipAddress) || HIGH_RANGE.equals(ipAddress)) { 55 return false; 56 } 57 return isValidAddress(ipAddress) || isValidRegexAddress(ipAddress) || isValidCIDRAddress(ipAddress); 58 } 59 60 private static boolean isValidAddress(String ipAddress) { 61 try { 62 InetAddress.getByName(ipAddress); 63 return containsFourNumbericParts(ipAddress); 64 } catch (UnknownHostException e) { 65 return false; 66 } 67 } 68 69 private static boolean containsFourNumbericParts(String ipAddress) { 70 int regionCount = 0; 71 for (StringTokenizer tokenizer = new StringTokenizer (ipAddress, "."); tokenizer.hasMoreTokens();) { 72 try { 73 String token = (String ) tokenizer.nextToken(); 74 Integer.parseInt(token); 75 regionCount++; 76 } catch (NumberFormatException e) { 77 return false; 78 } 79 } 80 return 4 == regionCount; 81 } 82 83 private static boolean isValidRegexAddress(String ipAddress) { 84 String replacedIpAddress = ipAddress.replace("*", "0"); 85 return isValidAddress(replacedIpAddress); 86 } 87 88 private static boolean isValidCIDRAddress(String ipAddress) { 89 try { 90 new CIDRNetwork(ipAddress); 91 return true; 92 } catch (Exception e) { 93 return false; 94 } 95 } 96 } 97 | Popular Tags |