I am using correto java 11 JDK
Here is my method:
public static boolean sendPingRequest(String host)
{
boolean value = false;
try
{
InetAddress myip = InetAddress.getByName(host);
System.out.println("Sending Ping Request to " + myip);
if (myip.isReachable(5000))
{
System.out.println("Host: " + host + " is reachable");
value = true;
}
else
{
System.out.println("Host: " + host + " is unreachable");
}
}
catch (UnknownHostException e)
{
System.out.println("I can't reach this host: " + e.getMessage());
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("IO Exception" + e.getMessage());
}
return value;
}
When I can the method here it fails
String myHost = "www.google.com";
sendPingRequest(myHost);
Sending Ping Request to www.google.com/108.177.111.106 Host: www.google.com is unreachable Process finished with exit code 0
From reading the documentation it looks like InetAddress.getByName method returns this but it will fail every time unless I can get it to show the host to be the IP 108.177.111.106.
I can't reproduce your issue. Here's what I tried:
public class Main {
public static void main(String[] args) {
System.out.println(sendPingRequest("www.google.com"));
System.out.println(sendPingRequest("74.125.195.106"));
System.out.println(sendPingRequest("108.177.111.106"));
}
public static boolean sendPingRequest(String host) {
boolean value = false;
try {
InetAddress myip = InetAddress.getByName(host);
System.out.println("Sending Ping Request to " + myip);
if (myip.isReachable(5000)) {
System.out.println("Host: " + host + " is reachable");
value = true;
} else {
System.out.println("Host: " + host + " is unreachable");
}
} catch (UnknownHostException e) {
System.out.println("I can't reach this host: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO Exception" + e.getMessage());
}
return value;
}
}
and the output is
Sending Ping Request to www.google.com/74.125.195.105
Host: www.google.com is reachable
true
Sending Ping Request to /74.125.195.106
Host: 74.125.195.106 is reachable
true
Sending Ping Request to /108.177.111.106
Host: 108.177.111.106 is reachable
true
Perhaps you were having network issues?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.