39

I am developing an application which connects to the server. By now the login and data transmission works fine if theserver is available. The problem arises when the server is unavailable. In this case the method sends a login request and waits for the response.

Does anyone know how to check if the server is available (visible)?

The pseudocode of the simple logic that has to be implemented is the following:

  1. String serverAddress = (Read value from configuration file) //already done
  2. boolean serverAvailable = (Check if the server serverAddress is available)//has to be implemented
  3. (Here comes the logic which depends on serverAvailable)
Guido
  • 46,642
  • 28
  • 120
  • 174
Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286

7 Answers7

51

He probably needs Java code since he's working on Android. The Java equivalent -- which I believe works on Android -- should be:

InetAddress.getByName(host).isReachable(timeOut)
Sean Owen
  • 66,182
  • 23
  • 141
  • 173
  • 31
    Beware that this doesn't always work! [From the docs](http://developer.android.com/reference/java/net/InetAddress.html#isReachable%28int%29): "This method first tries to use ICMP (ICMP ECHO REQUEST). When first step fails, a TCP connection on port 7 (Echo) of the remote host is established." I have found that many Android devices don't support ICMP, and many servers don't accept TCP connections over port 7. `isReachable()` then simply times out while the server is reachable. – Paul Lammertsma Aug 09 '11 at 07:46
  • you also need to use it asynchronously if used in main thread – redbeam_ May 15 '17 at 15:18
21

With a simple ping-like test, this worked for me :

static public boolean isURLReachable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://192.168.1.13");   // Change to "http://google.com" for www  test.
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(10 * 1000);          // 10 s.
            urlc.connect();
            if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
                Log.wtf("Connection", "Success !");
                return true;
            } else {
                return false;
            }
        } catch (MalformedURLException e1) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
    return false;
}

Do not forget to run this function in a thread (not in the main thread).

gfrigon
  • 2,237
  • 2
  • 23
  • 32
Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
  • Sorry, I was still looking for a solution yet. What i found out is running this in background is consuming lot of bandwidth as i suppose its downloading the while page in the background. So trying now with ping process currently. – Ayyappa Jun 07 '15 at 08:48
  • Ok, I see, thanks for the details. Feel free to edit my answer, or to provide your own ;) – Gauthier Boaglio Jun 07 '15 at 09:33
  • @Gauthier Boaglio : I tried with ping but its returning result as 2 without any success. The comment i made could be misleading to others so removing it now. Thanks for your time :) – Ayyappa Jun 09 '15 at 08:21
  • where's the permission ? did you write it somewhere...? – gumuruh Jun 03 '20 at 08:02
8

you can use

InetAddress.getByName(host).isReachable(timeOut)

but it doesn't work fine when host is not answering on tcp 7. You can check if the host is available on that port what you need with help of this function:

public static boolean isHostReachable(String serverAddress, int serverTCPport, int timeoutMS){
    boolean connected = false;
    Socket socket;
    try {
        socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(serverAddress, serverTCPport);
        socket.connect(socketAddress, timeoutMS);
        if (socket.isConnected()) {
            connected = true;
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        socket = null;
    }
    return connected;
}
adudakov
  • 212
  • 3
  • 6
4
public static boolean IsReachable(Context context) {
    // First, check we have any sort of connectivity
    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
    boolean isReachable = false;

    if (netInfo != null && netInfo.isConnected()) {
        // Some sort of connection is open, check if server is reachable
        try {
            URL url = new URL("http://www.google.com");
            //URL url = new URL("http://10.0.2.2");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("User-Agent", "Android Application");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(10 * 1000);
            urlc.connect();
            isReachable = (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            //Log.e(TAG, e.getMessage());
        }
    }

    return isReachable;
}

try it, work for me and dont forget actived android.permission.ACCESS_NETWORK_STATE

3
public boolean isConnectedToServer(String url, int timeout) {
try{
    URL myUrl = new URL(url);
    URLConnection connection = myUrl.openConnection();
    connection.setConnectTimeout(timeout);
    connection.connect();
    return true;
} catch (Exception e) {
    // Handle your exceptions
    return false;
 }
}
Iman Marashi
  • 5,593
  • 38
  • 51
2

Are you working with HTTP? You could then set a timeout on your HTTP connection, as such:

private void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, CONNECTION_TIMEOUT);
    //...

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
            httpParams, schemeRegistry);
    this.httpClient = new DefaultHttpClient(cm, httpParams);
}

If you then execute a request, you will get an exception after the given timeout.

mxk
  • 43,056
  • 28
  • 105
  • 132
0

Oh, no no, the code in Java doesn't work: InetAddress.getByName("fr.yahoo.com").isReachable(200) although in the LogCat I saw its IP address (the same with 20000 ms of time out).

It seems that the use of the 'ping' command is convenient, for example:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping fr.yahoo.com -c 1"); // other servers, for example
proc.waitFor();
int exit = proc.exitValue();
if (exit == 0) { // normal exit
    /* get output content of executing the ping command and parse it
     * to decide if the server is reachable
     */
} else { // abnormal exit, so decide that the server is not reachable
    ...
}
kinhnc
  • 9
  • 1
  • 12
    Seen as this is tagged Android, I'd like to save anybody the effort of trying this as opening raw sockets on Linux requires root permissions. Hence, it *will not work* on most unrooted devices. I have found it to work several HTC devices, but others simply return "ping: icmp open socket: Operation not permitted". – Paul Lammertsma Aug 09 '11 at 07:43