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?
In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress.
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.
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.
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.
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With