-
Notifications
You must be signed in to change notification settings - Fork 1
/
NetworkUtils.java
63 lines (55 loc) · 2.03 KB
/
NetworkUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.example.jeffreynyauke.myapplication.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
/**
* Created by CaptofOuterSpace on 12/16/2016.
*/
public class NetworkUtils {
public static boolean isServerAvailable(){
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) {
}
return exists;
}
static public boolean isServerReachable(Context context) {
ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL urlServer = new URL("your server url");
HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout
urlConn.connect();
if (urlConn.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
return false;
}
// exists = InetAddress.getByName(host).isReachable(timeOut);
}