Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a String is an IP in Groovy?

From a given String:

String someIp = // some String

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

like image 925
confile Avatar asked Aug 09 '13 23:08

confile


People also ask

Can IP address be a string?

An IP address is a string of numbers separated by periods. IP addresses are expressed as a set of four numbers — an example address might be 192.158.1.38. Each number in the set can range from 0 to 255. So, the full IP addressing range goes from 0.0.0.0 to 255.255.255.255.

How do I find my groovy IP address?

This requires a call to InetAddress. getByName() in the Java API. If the URL already has the address then InetAddress. getByName() will simply return the address as-is.

What is the regex for IP address?

// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."

How do you check if a string matches a regex in groovy?

Groovy regular expressions have a ==~ operator which will determine if your string matches a given regular expression pattern.


1 Answers

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..,.

like image 88
MKB Avatar answered Sep 22 '22 18:09

MKB