001/** 002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC 003 * and GZip files. (http://jwat.org/) 004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/) 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); 007 * you may not use this file except in compliance with the License. 008 * You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.jwat.common; 019 020import java.net.InetAddress; 021import java.net.UnknownHostException; 022import java.util.regex.Pattern; 023 024/** 025 * IP address parser and format validator for Ipv4 and Ipv6. 026 * 027 * @author lbihanic, selghissassi 028 */ 029public final class IPAddressParser { 030 031 /** Regular expression for Ipv4 or Ipv6 address. */ 032 private static final String IP_ADDRESS_REG_EXP = 033 "([0-9a-fA-F]{0,4}:){0,6}(" // Optional IPv6 start 034 + "([0-9a-fA-F]{0,4}:[0-9a-fA-F]{1,4})|" // True IPv6 address or 035 + "(([0-9]{1,3}\\.){3}[0-9]{1,3}))"; // Standalone or mixed IPv4 address 036 037 /** IpAddress compiled regex pattern. */ 038 private static final Pattern IP_ADDRESS_PATTERN 039 = Pattern.compile(IP_ADDRESS_REG_EXP); 040 041 /** 042 * Checks the validity of an IP address. 043 * Supports both IP v4 and IP v6 formats. 044 * @param ipAddress the IP address 045 * @return the inetAddress of the IP address if valid, if not, null is returned 046 */ 047 public static InetAddress getAddress(String ipAddress){ 048 boolean isValid = (ipAddress == null) ? false 049 : IP_ADDRESS_PATTERN.matcher(ipAddress).matches(); 050 InetAddress inetAddress = null; 051 if(isValid){ 052 try { 053 inetAddress = InetAddress.getByName(ipAddress); 054 } catch (UnknownHostException e) { 055 isValid = false; 056 } 057 } 058 return (isValid) ? inetAddress : null; 059 } 060 061 /** 062 * No constructor for this utility class, static access only. 063 */ 064 protected IPAddressParser() { 065 } 066 067}