Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get IP address from a String(Groovy)

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
like image 734
Bhanu Prakash Dixit Avatar asked Dec 05 '12 11:12

Bhanu Prakash Dixit


2 Answers

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
like image 176
tim_yates Avatar answered Nov 08 '22 07:11

tim_yates


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
like image 4
CodeMonkey Avatar answered Nov 08 '22 08:11

CodeMonkey