0

I am trying to check rechability of host by following code :

 Socket socket = new Socket();

     try 
     {
         SocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName("https://www.google.co.in"), 80);
         socket.connect(socketAddress, 2000);
     }
     catch (IOException e) 
     {
        Log.e("server",e.getMessage());
         return false;
     }
     finally 
     {
         if (socket.isConnected()) {
             try {
                socket.close();
             }
             catch (IOException e) {
                 e.printStackTrace();
             }
         }
    }
     return true;

but it always returns false. is there anything else that needs to be added. It gives unresolved host url exception.

Rujul1993
  • 1,631
  • 2
  • 10
  • 10
  • Remove 'https://' from the url. Why using port 80 and 2000? HTTPS has a different port. – greenapps Jul 14 '14 at 17:01
  • Thank you. actually i replaced my sites url with google's and forgot to change the port number. the 2000 is the timeout period. – Rujul1993 Jul 14 '14 at 17:10
  • It's still giving following error : failed to connect to www.google.co.in/74.125.130.94 (port 443) after 2000ms – Rujul1993 Jul 14 '14 at 17:12

1 Answers1

0

Try this instead:

public static boolean ping(String url, int timeout) {
    url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}

With this you are pinging a website, like google, so you can check the Reachability.

mapodev
  • 988
  • 8
  • 14