How to check if String IP is in Groovy?

From this line:

String someIp = // some String 

How to check if someIp is a valid ip format?

+7
java grails groovy
source share
3 answers

You can use the InetAddressValidator class to check and check the weather whether the string is a valid ip or not.

 import org.codehaus.groovy.grails.validation.routines.InetAddressValidator ... String someIp = // some String if(InetAddressValidator.getInstance().isValidInet4Address(someIp)){ println "Valid Ip" } else { println "Invalid Ip" } ... 

Try it.,.

+12
source share

Regular expressions will be executed. There are simple and more complex ones. Simple is this regular expression:

 \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} 

Use it as follows:

 boolean isIP = someIP.maches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); 

But it will also correspond to 999.999.999.999, which is not a valid IP address. There is a huge regex available at regular-expressions.info :

 (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) 

This person will take care of the job properly. If you use this, be sure to avoid each \ other \ .


If you are not a fan of huge regular expressions, you can use this code:

 public static boolean isIP(String str) { try { String[] parts = str.split("\\."); if (parts.length != 4) return false; for (int i = 0; i < 4; ++i) { int p = Integer.parseInt(parts[i]); if (p > 255 || p < 0) return false; } return true; } catch (Exception e) { return false; } } 
+3
source share

Oriented Object:

 String myIp ="192.168.43.32" myIp.isIp(); 

It is known that you should add this to BootStrap.groovy :

 String.metaClass.isIp={ if(org.codehaus.groovy.grails.validation.routines.InetAddressValidator.getInstance().isValidInet4Address(delegate)){ return true; } else { return false; } } 
+1
source share

All Articles