Java 语言实现 IPv6 是否ping通
Java 语言实现 IPv6 是否ping通
1、导入相关的 Java 网络库
import java.net.InetAddress;
import java.net.UnknownHostException;
2、定义 ping 方法,传入目标 IPv6 地址
public static boolean ping(String ipv6Address) {
boolean isPingSuccessful = false;
try {
InetAddress inet = InetAddress.getByName(ipv6Address);
isPingSuccessful = inet.isReachable(5000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isPingSuccessful;
}
3、在方法中,使用 InetAddress 类中的 getByName 方法获取目标 IPv6 地址的 InetAddress 实例。
4、使用 InetAddress 实例的 isReachable 方法来判断是否能够连接到目标 IPv6 地址。如果能够连接,则 isReachable 方法返回 true,否则返回 false。
5、使用 try-catch 语句来捕捉 UnknownHostException 和 IOException 异常。
6、最后,返回 ping 是否成功的 boolean 值。
示例代码如下:
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.IOException;
public class IPv6Ping {
public static boolean ping(String ipv6Address) {
boolean isPingSuccessful = false;
try {
InetAddress inet = InetAddress.getByName(ipv6Address);
isPingSuccessful = inet.isReachable(5000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isPingSuccessful;
}
public static void main(String[] args) {
String ipv6Address = "2001:4860:4860::8888";
boolean isPingSuccessful = ping(ipv6Address);
if(isPingSuccessful) {
System.out.println("Ping " + ipv6Address + " successful!");
} else {
System.out.println("Ping " + ipv6Address + " failed!");
}
}
}
运行结果如下:
Ping 2001:4860:4860::8888 successful!