Finding IP address of a URL in Java
Last Updated :
13 Mar, 2024
Prerequisite: InetAddress
getByName() : Returns the InetAddress of the given host. If the host is a literal IP address, then only its validity is checked. Fetches public IP Address of the host specified. It takes the host as an argument and returns the corresponding IP address.
Examples:
Input : www.google.com
Output : 216.58.199.164
Input : localhost
Output : 127.0.0.1
Below programs illustrate how to fetch public IP addresses:
Note: These programs won’t run on online compilers. Use offline compilers like Netbeans, Eclipse, etc, instead.
Program 1: Fetch IP address of any URL
Java
import java.net.*;
import java.*;
class GFG {
public static void main(String args[])
throws UnknownHostException
{
try {
InetAddress ip = InetAddress.getByName( new URL(s)
.getHost());
System.out.println( "Public IP Address of: " + ip);
}
catch (MalformedURLException e) {
System.out.println( "Invalid URL" );
}
}
}
|
Output:
Public IP Address of: www.google.com/216.58.196.164
Program 2: Fetch the public IP address of one’s system
To find public IP, use http://bot.whatismyipaddress.com. It is an online utility, to find the system’s public IP. Open the URL, read a line and print the line.
Java
import java.net.*;
import java.*;
class GFG {
public static void main(String args[])
throws UnknownHostException
{
String systemipaddress = "" ;
try {
BufferedReader sc = new BufferedReader(
new InputStreamReader(url_name.openStream()));
systemipaddress = sc.readLine().trim();
}
catch (Exception e) {
systemipaddress = "Cannot Execute Properly" ;
}
System.out.println( "Public IP Address: "
+ systemipaddress + "\n" );
}
}
|
Output:
Public IP Address: 103.62.239.242
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...