0

I am trying to check if server is online in android. I have following code on a button onclick listener block:

                boolean exists = false;

            try {
                SocketAddress sockaddr = new InetSocketAddress("google.com", 80);
                // Create an unbound socket
                Socket sock = new Socket();

                // This method will block no more than timeoutMs.
                // If the timeout occurs, SocketTimeoutException is thrown.
                int timeoutMs = 2000;   // 2 seconds
                sock.connect(sockaddr, timeoutMs);
                exists = true;
            }catch(Exception e){
            }
            if ( exists == true) {
                Toast.makeText(getApplicationContext(), "Host is reachable!!! =)",
                        Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getApplicationContext(), "Host is NOT reachable!!! =(",
                        Toast.LENGTH_LONG).show();
            }

Thing is that, whatever host or ip i check, its always offline.

What could be the problem?

I have this permission in androidmanifest:

    <uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE"/>
user2033139
  • 573
  • 2
  • 10
  • 21

2 Answers2

0

Try this

InetAddress.getByName(host).isReachable(timeOut)

or

boolean exists = false;

try {
    SocketAddress sockaddr = new InetSocketAddress(ip, port);
    // Create an unbound socket
    Socket sock = new Socket();

    // This method will block no more than timeoutMs.
    // If the timeout occurs, SocketTimeoutException is thrown.
    int timeoutMs = 2000;   // 2 seconds
    sock.connect(sockaddr, timeoutMs);
    exists = true;
}catch(Exception e){
}
Fahim
  • 12,198
  • 5
  • 39
  • 57
  • As i understand, isReachable is not reliable in android: http://stackoverflow.com/questions/9922543/why-does-inetaddress-isreachable-return-false-when-i-can-ping-the-ip-address – user2033139 Feb 18 '15 at 15:08
0

I prefer to use HttpClient. Something like:

getURL = "http://www.msftncsi.com/ncsi.txt"


HttpGet getHttp   = new HttpGet(getURL);
HttpParams httpParameters = new BasicHttpParams();

int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

int timeoutSocket     = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

HttpClient client = new DefaultHttpClient(httpParameters); 

HttpResponse responseGet = client.execute(getHttp);  
HttpEntity resEntityGet = responseGet.getEntity(); 

If HttpEntity returns null then I assume there is no connectivity.

You must surround with try catch and assume there is no connectivity when enter in the catch

Nacles
  • 1
  • 2