7

From a given String:

String someIp = // some String

How can I check, if someIp is a valid Ip format?

confile
  • 30,949
  • 47
  • 199
  • 357

3 Answers3

12

You can use InetAddressValidator class to check and validate weather a 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 this..,.

MKB
  • 7,475
  • 9
  • 42
  • 70
3

Regexes will do. There are simple ones and more complex. A simple one is this regex:

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

Use it like this:

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

But this will match 999.999.999.999 as well, which is not a valid IP address. There is a huge regex available on 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 one will take care of the job correctly. If you use this one, don't forget to escape every \ with another \.


If you are not a fan of huge regexes, 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;
    }
}
Martijn Courteaux
  • 65,802
  • 45
  • 192
  • 282
  • 2
    This is the superior answer, and he clearly knows REGEX in java better than I do, go with this one. I'm fairly new to the world of REGEX, and haven't used it in JAVA much yet. – CamelopardalisRex Aug 10 '13 at 00:00
  • Very good. Also, in Groovy, you can use `/regex/` string, thus not needing escapes, and use `==~` operator to check the regex match – Will Aug 10 '13 at 01:13
1

An oriented object way:

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

Known that , you must add this to BootStrap.groovy:

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


}
Abdennour TOUMI
  • 76,783
  • 33
  • 229
  • 231