From a given String:
String someIp = // some String
How can I check, if someIp is a valid Ip format?
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..,.
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;
}
}
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;
}
}
commons-validator
:@Grab('commons-validator:commons-validator:1.7')
import org.apache.commons.validator.routines.InetAddressValidator
boolean isIpV4(String ip) {
InetAddressValidator.instance.isValidInet4Address(ip)
}
isIpV4("8.8.8.8")
import java.util.regex.Pattern
class RegexValidationConstants {
private final static String IPV4_OCT = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/
final static Pattern IPV4 = ~/^${IPV4_OCT}(\.${IPV4_OCT}){3}$/.toString()
}
boolean isIpV4(String ip) {
ip ==~ RegexValidationConstants.IPV4
}
isIpV4("8.8.8.8")
If you are using Grails, see my answer in this other thread.