在Java中验证IPv4地址

时间:2011-04-14 17:49:14

标签: java ip-address

我想使用Java验证IPv4地址。它应该使用dot-decimal notation编写,因此它应该有3个点(“.”),没有字符,点之间有数字,数字应该在有效范围内。应该怎么做?

20 个答案:

答案 0 :(得分:84)

使用正则表达式非常简单(但请注意,与使用Apache Commons Utility的worpet的答案相比,这样效率更低,更难阅读)

private static final Pattern PATTERN = Pattern.compile(
        "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");

public static boolean validate(final String ip) {
    return PATTERN.matcher(ip).matches();
}

基于帖子Mkyong

答案 1 :(得分:50)

答案 2 :(得分:20)

使用Guava

InetAddresses.isInetAddress(ipStr)

答案 3 :(得分:9)

您可以使用正则表达式,如下所示:

(([0-1]?[0-9]{1,2}\.)|(2[0-4][0-9]\.)|(25[0-5]\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))

这个验证了值是否在范围内。

Android支持正则表达式。请参阅java.util.regex.Pattern

class ValidateIPV4
{

   static private final String IPV4_REGEX = "(([0-1]?[0-9]{1,2}\\.)|(2[0-4][0-9]\\.)|(25[0-5]\\.)){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))";
   static private Pattern IPV4_PATTERN = Pattern.compile(IPV4_REGEX);

   public static boolean isValidIPV4(final String s)
   {          
      return IPV4_PATTERN.matcher(s).matches();
   }
}

为避免反复重新编译模式,最好放置Pattern.compile()调用,使其仅执行一次。

答案 4 :(得分:7)

还有一个未记录的实用工具类sun.net.util.IPAddressUtilyou should not actually use,尽管它可能对快速的一次性丢弃实用程序很有用:

boolean isIP = IPAddressUtil.isIPv4LiteralAddress(ipAddressString);

在内部,这是实用程序类InetAddress用于解析IP地址。

请注意,对于像“123”这样的字符串,这将返回true,技术上是valid IPv4 addresses,而不是点十进制表示法。

答案 5 :(得分:7)

您可以使用此功能 -

public static boolean validate(final String ip) {
    String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";

    return ip.matches(PATTERN);
}

答案 6 :(得分:3)

这适用于Android,测试IPv4和IPv6

注意:不推荐使用常用的InetAddressUtils。使用新的InetAddress

public static Boolean isIPv4Address(String address) {
    if (address.isEmpty()) {
        return false;
    }
    try {
        Object res = InetAddress.getByName(address);
        return res instanceof Inet4Address || res instanceof Inet6Address
    } catch (final UnknownHostException ex) {
        return false;
    }
}

答案 7 :(得分:2)

如果是IP4,您可以使用正则表达式,如下所示:

^(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)\\.){3}(2[0-5][0-5])|(1\\d\\d)|([1-9]?\\d)$

答案 8 :(得分:2)

The IPAddress Java library会这样做。链接中提供了javadoc。免责声明:我是项目经理。

此库透明地支持IPv4和IPv6,因此验证在下面的工作方式相同,并且它也支持CIDR子网。

验证地址是否有效

    String str = "1.2.3.4";
    IPAddressString addrString = new IPAddressString(str);
    try {
         IPAddress addr = addrString.toAddress();
         ...
    } catch(AddressStringException e) {
        //e.getMessage provides validation issue
    }

答案 9 :(得分:1)

编写一个合适的正则表达式并对其进行验证。 JVM完全支持正则表达式。

答案 10 :(得分:1)

有很多方法可以实现这一点,但正则表达式更有效。

请看下面的代码:

public static void main(String[] args) {

    String ipStr1 = "255.245.188.123"; // valid IP address
    String ipStr2 = "255.245.188.273"; // invalid IP address - 273 is greater than 255

    validateIP(ipStr1);
    validateIP(ipStr2);
}

public static void validateIP(String ipStr) {
    String regex = "\\b((25[0–5]|2[0–4]\\d|[01]?\\d\\d?)(\\.)){3}(25[0–5]|2[0–4]\\d|[01]?\\d\\d?)\\b";
    System.out.println(ipStr + " is valid? " + Pattern.matches(regex, ipStr));
}

答案 11 :(得分:1)

正则表达式是解决此问题的最有效方法。 看下面的代码。在有效性方面,它还检查它所属的IP地址类以及它是否是保留的IP地址

Pattern ipPattern;
int[] arr=new int[4];
int i=0;

//Method to check validity
 private String validateIpAddress(String ipAddress) {
      Matcher ipMatcher=ipPattern.matcher(ipAddress);

        //Condition to check input IP format
        if(ipMatcher.matches()) {       

           //Split input IP Address on basis of .
           String[] octate=ipAddress.split("[.]");     
           for(String x:octate) { 

              //Convert String number into integer
              arr[i]=Integer.parseInt(x);             
              i++;
         }

        //Check whether input is Class A IP Address or not
         if(arr[0]<=127) {                          
             if(arr[0]==0||arr[0]==127)
                 return(" is Reserved IP Address of Class A");
             else if(arr[1]==0&&arr[2]==0&&arr[3]==0)
                 return(" is Class A Network address");
             else if(arr[1]==255&&arr[2]==255&&arr[3]==255)
                 return( " is Class A Broadcast address");
             else 
                 return(" is valid IP Address of Class A");
         }

        //Check whether input is Class B IP Address or not
         else if(arr[0]>=128&&arr[0]<=191) {        
             if(arr[2]==0&&arr[3]==0)
                 return(" is Class B Network address");
             else if(arr[2]==255&&arr[3]==255)
                 return(" is Class B Broadcast address");
             else
                 return(" is valid IP Address of Class B");
         }

        //Check whether input is Class C IP Address or not
         else if(arr[0]>=192&&arr[0]<=223) {        
             if(arr[3]==0)
                 return(" is Class C Network address");
             else if(arr[3]==255)
                 return(" is Class C Broadcast address");
             else
                 return( " is valid IP Address of Class C");
        }

        //Check whether input is Class D IP Address or not
        else if(arr[0]>=224&&arr[0]<=239) {          
             return(" is Class D IP Address Reserved for multicasting");
        }

        //Execute if input is Class E IP Address
        else  {                                   
             return(" is Class E IP Address Reserved for Research and Development by DOD");
        }

    }

    //Input not matched with IP Address pattern
    else                                     
        return(" is Invalid IP Address");


}


public static void main(String[] args) {

    Scanner scan= new Scanner(System.in);
    System.out.println("Enter IP Address: ");

    //Input IP Address from user
    String ipAddress=scan.nextLine();  
    scan.close();
    IPAddress obj=new IPAddress();

    //Regex for IP Address
    obj.ipPattern=Pattern.compile("((([0-1]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([0-1]?\\d\\d?|2[0-4]\\d|25[0-5]))");

    //Display output
    System.out.println(ipAddress+ obj.validateIpAddress(ipAddress));

}

答案 12 :(得分:0)

 private static final String IPV4_PATTERN_ALLOW_LEADING_ZERO =
            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
            "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

答案 13 :(得分:0)

我的解决方案(支持前导0):

   String pattern="^[0-9](\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25?[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?$";

答案 14 :(得分:0)

apache-httpcomponents的库

// ipv4 is true
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
// not detect the ipv6
assertFalse(InetAddressUtils.isIPv4Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));

Maven库(2019年9月更新)

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

答案 15 :(得分:0)

/**
 * Check if ip is valid
 *
 * @param ip to be checked
 * @return <tt>true</tt> if <tt>ip</tt> is valid, otherwise <tt>false</tt>
 */
private static boolean isValid(String ip) {
    String[] bits = ip.split("\\.");
    if (bits.length != 4) {
        return false;
    }
    for (String bit : bits) {
        try {
            if (Integer.valueOf(bit) < 0 || Integer.valueOf(bit) > 255) {
                return false;
            }
        } catch (NumberFormatException e) {
            return false; /* contains other other character */
        }
    }
    return true;
}

答案 16 :(得分:0)

使用正则表达式在两行中获取有效的IP地址。请检查代码的注释会话,以了解正则表达式如何工作以获取数字范围。

delete

答案 17 :(得分:0)

all active threads in current thread group

答案 18 :(得分:0)

如果您不关心范围,以下表达式将有助于验证从1.1.1.1到999.999.999.999

"[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}\\.[1-9]{1,3}"

答案 19 :(得分:0)

请查看 sun.net.util 中的 IPAddressUtil OOTB类,这对您有所帮助。