Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate IPv4 address in Java

I want to validate an IPv4 address using Java. It should be written using the dot-decimal notation, so it should have 3 dots ("."), no characters, numbers in between the dots, and numbers should be in a valid range. How should it be done?

like image 444
iRunner Avatar asked Apr 14 '11 17:04

iRunner


People also ask

How do I find my IPv4 address in Java?

In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress.

How do I know if an IP address is valid?

A valid IP address must be in the form of A.B.C.D, where A,B,C and D are numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0. Note:You only need to implement the given function.

Is IP address in Java?

Java's InetAddress class represents an IP address and provides methods to get the IP for any given hostnames. An instance of InetAddress represents the IP address with its corresponding hostname. The above logic of converting an IP address to an integer also applies to IPv6, but it's a 128-bit integer.

How do I find out if my IP address is IPv4 or IPv6?

By using I-P. show, you can check whether you are: On an IPv4 supported device here: https://v4.i-p.show. On an IPv6 supported device here: https://v6.i-p.show.


2 Answers

Pretty simple with Regular Expression (but note this is much less efficient and much harder to read than worpet's answer that uses an Apache Commons Utility)

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(); } 

Based on post Mkyong

like image 130
Necronet Avatar answered Oct 03 '22 22:10

Necronet


Try the InetAddressValidator utility class.

Docs here:

http://commons.apache.org/validator/apidocs/org/apache/commons/validator/routines/InetAddressValidator.html

Download here:

http://commons.apache.org/validator/

like image 23
worpet Avatar answered Oct 03 '22 22:10

worpet