I wrote the following code to try a ping
. But as I run it, the following exception gets thrown :
java.net.UnknownHostException: http://localhost:8084/server/index.jsp
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getByName(Unknown Source)
at Tester.main(Tester.java:10)
import java.net.InetAddress;
class Tester {
public static void main(String args[]) {
try {
InetAddress address = InetAddress.getByName("http://localhost:8084/server/index.jsp");
boolean isReachable = address.isReachable(2000);
if(isReachable)
System.out.println("The address is reachable");
else
System.out.println("The address is not reachable");
} catch(Exception exc) {
exc.printStackTrace();
}
}
}
Why is it so ? The server is running and the page is opening fine in the web-browser.
The problem is in this line:
InetAddress address = InetAddress.getByName(
"http://localhost:8084/server/index.jsp");
The InetAddress.getByName(String)
method requires a hostname. You've given it a URL string. The hostname component of that address is "localhost"
.
If you want to "ping" the host associated with a URL, then you need to parse the URL and extract the hostname component something like this:
String hostname = new URL(str).getHost();
But you need to deal with the cases where the URL is malformed, or where it doesn't have a host name component.
I imagine that you are actually trying to test some other hostname, because sending an ICMP_PING request to "localhost"
(typically 127.0.0.1
) is kind of pointless.