javainetaddress

Java InetAddress failed


I am trying to check if some host is reachable using the "isReachable" method.

line 113: oaiBaseURL = "http://www.cnn.com";//////////////////////////////////////
line 114: boolean res = InetAddress.getByName(oaiBaseURL).isReachable(10000);
line 115: System.out.println("------reachable:"+res);

and get the following error message (in eclipse):

java.net.UnknownHostException: http://www.cnn.com
    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.getAllByName(Unknown Source)
    at java.net.InetAddress.getAllByName(Unknown Source)
    at java.net.InetAddress.getByName(Unknown Source)
    at com.irWizard.web.validator.WizardValidator.validateForm(WizardValidator.java:114)

Does anyone understand what might be the reason for this error?

Thanks in advance!


Solution

  • You need to remove the http:// prefix.

    As far as I know the InetAddress.getByName() method takes a hostname not a URL.

    You can change the code as follows:

       URL url = new URL("http://www.cnn.com");
       boolean res = InetAddress.getByName(url.getHost()).isReachable(10000);
       System.out.println("------reachable:"+res);
    

    However keep in mind the mechanisms the method isReachable() uses to determine whether it is reachable or not. It uses mostly ICMP techniques, which a lot of websites or intermediate firewalls might block.