This post shows the steps and code required to get the IP of a website. It expects a valid website URL in order to query the same to get the IP.
The basic code to get the IP of a website is as shown below.
// Stores the site URL String siteUrl = "https://www.google.com";
// Convert the String to URL URL url = new URL( siteUrl );
// Create address object InetAddress ip = InetAddress.getByName( url.getHost() );
// Get the IP System.out.println( ip.getHostAddress() );
Below is the fully implemented and tested code to show the IP of the given website URL.
package networking;
import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException;
public class ShowIp { public static void main( String args[] ) {
// Stores the site URL String siteUrl = "https://www.google.com"; ShowIp ipUtil = new ShowIp(); InetAddress ip = ipUtil.getWebsiteIp( siteUrl );
// Print the address if( null != ip ) { System.out.println( "The IP Address of given site URL - " + siteUrl + " is: " + ip.getHostAddress() ); }
// Show error else {
System.out.println( "IP not found for given URL" ); } }
/** * Get and return the IP address using the given Web URL. */
public InetAddress getWebsiteIp( String siteUrl ) { InetAddress ip = null;
try {
// Convert the String to URL URL url = new URL( siteUrl );
// Create address object ip = InetAddress.getByName( url.getHost() ); }
// URL not formatted catch( MalformedURLException e ) {
System.out.println( "Invalid URL found" ); }
// Host not found catch( UnknownHostException e ) {
System.out.println( "Host not found" ); }
// Returns address object return ip; } }