在Java中查找 URL 的 IP 地址
先决条件:InetAddress
getByName() :返回给定主机的 InetAddress。如果主机是字面量IP 地址,则只检查其有效性。获取指定主机的公共 IP 地址。它将主机作为参数并返回相应的 IP 地址。
例子:
Input : www.google.com
Output : 216.58.199.164
Input : localhost
Output : 127.0.0.1
下面的程序说明了如何获取公共 IP 地址:
注意:这些程序不会在在线编译器上运行。请改用 Netbeans、Eclipse 等离线编译器。
程序 1:获取任意 URL 的 IP 地址
Java
// Java program to demonstrate
// how to fetch public IP Address
import java.net.*;
import java.*;
class GFG {
public static void main(String args[])
throws UnknownHostException
{
// The URL for which IP address needs to be fetched
String s = "https:// www.google.com/";
try {
// Fetch IP address by getByName()
InetAddress ip = InetAddress.getByName(new URL(s)
.getHost());
// Print the IP address
System.out.println("Public IP Address of: " + ip);
}
catch (MalformedURLException e) {
// It means the URL is invalid
System.out.println("Invalid URL");
}
}
}
Java
// Java program to demonstrate
// how to fetch public IP Address
import java.net.*;
import java.*;
class GFG {
public static void main(String args[])
throws UnknownHostException
{
String systemipaddress = "";
try {
URL url_name = new URL("http://bot.whatismyipaddress.com");
BufferedReader sc = new BufferedReader(
new InputStreamReader(url_name.openStream()));
// reads system IPAddress
systemipaddress = sc.readLine().trim();
}
catch (Exception e) {
systemipaddress = "Cannot Execute Properly";
}
// Print IP address
System.out.println("Public IP Address: "
+ systemipaddress + "\n");
}
}
输出:
Public IP Address of: www.google.com/216.58.196.164
程序2:获取系统的公共IP地址
要查找公共 IP,请使用 http://bot.whatismyipaddress.com。它是一个在线实用程序,用于查找系统的公共 IP。打开 URL,读取一行并打印该行。
Java
// Java program to demonstrate
// how to fetch public IP Address
import java.net.*;
import java.*;
class GFG {
public static void main(String args[])
throws UnknownHostException
{
String systemipaddress = "";
try {
URL url_name = new URL("http://bot.whatismyipaddress.com");
BufferedReader sc = new BufferedReader(
new InputStreamReader(url_name.openStream()));
// reads system IPAddress
systemipaddress = sc.readLine().trim();
}
catch (Exception e) {
systemipaddress = "Cannot Execute Properly";
}
// Print IP address
System.out.println("Public IP Address: "
+ systemipaddress + "\n");
}
}
输出:
Public IP Address: 103.62.239.242