Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating IPv4 string in Java

Bellow method is validating if string is correct IPv4 address it returns true if it is valid. Any improvements in regex and elegance would be very appreciated:

public static boolean validIP(String ip) {     if (ip == null || ip.isEmpty()) return false;     ip = ip.trim();     if ((ip.length() < 6) & (ip.length() > 15)) return false;      try {         Pattern pattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");         Matcher matcher = pattern.matcher(ip);         return matcher.matches();     } catch (PatternSyntaxException ex) {         return false;     } } 
like image 606
MatBanik Avatar asked Jan 03 '11 03:01

MatBanik


People also ask

How do you validate a string in Java?

In Java you can use the String. matches(String regex) method. With regexes we say you match a string against a pattern If a match is successful, . matches() returns true.

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.

What is IPv4 in Java?

IPv4 is a version 4 of IP. It is a current version and the most commonly used IP address. It is a 32-bit address written in four numbers separated by 'dot', i.e., periods. This address is unique for each device. For example, 66.94.29.13.


1 Answers

Here is an easier-to-read, slightly less efficient, way you could go about it.

public static boolean validIP (String ip) {     try {         if ( ip == null || ip.isEmpty() ) {             return false;         }          String[] parts = ip.split( "\\." );         if ( parts.length != 4 ) {             return false;         }          for ( String s : parts ) {             int i = Integer.parseInt( s );             if ( (i < 0) || (i > 255) ) {                 return false;             }         }         if ( ip.endsWith(".") ) {             return false;         }          return true;     } catch (NumberFormatException nfe) {         return false;     } } 
like image 86
rouble Avatar answered Sep 21 '22 15:09

rouble