I want to extract the IP and return it . Something like
def getIPfromString ( myString ) {
..
return IP
}
IP = getIPfromString("ftp://192.168.13.108/720_prev")
print " IP Address : " + IP
Output :
IP Address : 192.168.13.108
You can use Java's URL class with a dash of Groovy magic ;-)
String getAddressFromString( String url ) {
url.toURL().host
}
String ip = getAddressFromString( 'ftp://192.168.13.108/720_prev' )
println "IP Address : $ip"
which (as requested) outputs:
IP Address : 192.168.13.108
If The URL already has the IP address then converting to a URL works to extract the IP but if a domain host name (e.g. www.stackoverflow.com) is found in the URL host component then need to perform a DNS lookup that resolves to an 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. Also, need to address handling of exceptions if host name cannot be resolved to an address.
String getAddressFromString( String url )
throws MalformedURLException, UnknownHostException
{
String host = url.toURL().host
// this would be equivalent to calling new URL(url).getHost()
return InetAddress.getByName(host).getHostAddress()
}
String ip = getAddressFromString( "http://stackoverflow.com/" )
println "IP Address : $ip"
Output:
IP Address : 69.59.197.21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With