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"/>