How to Check If Internet Connection Is Present in Java

How to check if internet connection is present in Java?

You should connect to the place that your actual application needs. Otherwise you're testing whether you have a connection to somewhere irrelevant (Google in this case).

In particular, if you're trying to talk to a web service, and if you're in control of the web service, it would be a good idea to have some sort of cheap "get the status" web method. That way you have a much better idea of whether your "real" call is likely to work.

In other cases, just opening a connection to a port that should be open may be enough - or sending a ping. InetAddress.isReachable may well be an appropriate API for your needs here.

Checking if PC has internet connectivity using Java

Try using InetAddress.isReachable()

Java Quickly check for network connection

From JGuru

Starting with Java 5, there is an isReachable() method in the
InetAddress class. You can specify either a timeout or the
NetworkInterface to use. For more information on the underlying
Internet Control Message Protocol (ICMP) used by ping, see RFC 792
(http://www.faqs.org/rfcs/rfc792.html).

Usage from Java2s

  int timeout = 2000;
InetAddress[] addresses = InetAddress.getAllByName("www.google.com");
for (InetAddress address : addresses) {
if (address.isReachable(timeout))
System.out.printf("%s is reachable%n", address);
else
System.out.printf("%s could not be contacted%n", address);
}

If you want to avoid blocking use Java NIO (Non-blocking IO) in the java.nio package

String host = ...; 
InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(socketAddress);

Detect internet Connection using Java

That's a perfectly reasonable approach to solving the problem. The bad thing is that you are really testing DNS rather than testing the whole network, but in practice you can often get by with treating those as equivalent.

The other thing to remember, is that you will need to set a system property to turn off dns caching in the java runtime. Otherwise it may continue to report that the network is up based upon cached data (even though it is down).

Another approach would be to actually open an HTTP request to some network address such as this every so often.

How to check internet connectivity in Java

The only way I am aware of is sending a packet to some known host, known in the sense that you know it will always be up and running and reachable from the calling site.

However, for example, if you choose a named host, the ping may fail due to a DNS lookup failure.

I think you shouldn't worry about this problem: if your program needs an Internet connection, it's because it sends or receives data. Connections are not a continuous concept like a river, but are more like a road. So just use the Java standard for dealing with connection errors: IOExceptiions. When your program must send data, the underlying API will certailnly throw an IOE in the case the network is down. If your program expects data, instead, use a timeout or something like that to detect possible errors in the network stack and report it to the user.

How to check internet access on Android? InetAddress never times out

Network connection / Internet access

  • isConnectedOrConnecting() (used in most answers) checks for any network connection
  • To know whether any of those networks have internet access, use one of the following

A) Ping a Server (easy)

// ICMP 
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }

return false;
}

+ could run on main thread

- does not work on some old devices (Galays S3, etc.), it blocks a while if no internet is available.

B) Connect to a Socket on the Internet (advanced)

// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
try {
int timeoutMs = 1500;
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

sock.connect(sockaddr, timeoutMs);
sock.close();

return true;
} catch (IOException e) { return false; }
}

+ very fast (either way), works on all devices, very reliable

- can't run on the UI thread

This works very reliably, on every device, and is very fast. It needs to run in a separate task though (e.g. ScheduledExecutorService or AsyncTask).

Possible Questions

  • Is it really fast enough?

    Yes, very fast ;-)

  • Is there no reliable way to check internet, other than testing something on the internet?

    Not as far as I know, but let me know, and I will edit my answer.

  • What if the DNS is down?

    Google DNS (e.g. 8.8.8.8) is the largest public DNS in the world. As of 2018 it handled over a trillion queries a day [1]. Let 's just say, your app would probably not be the talk of the day.

  • Which permissions are required?

    <uses-permission android:name="android.permission.INTERNET" />

    Just internet access - surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about internet access, without this permission?)

 

Extra: One-shot RxJava/RxAndroid Example (Kotlin)

fun hasInternetConnection(): Single<Boolean> {
return Single.fromCallable {
try {
// Connect to Google DNS to check for connection
val timeoutMs = 1500
val socket = Socket()
val socketAddress = InetSocketAddress("8.8.8.8", 53)

socket.connect(socketAddress, timeoutMs)
socket.close()

true
} catch (e: IOException) {
false
}
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

hasInternetConnection().subscribe { hasInternet -> /* do something */}

Extra: One-shot RxJava/RxAndroid Example (Java)

public static Single<Boolean> hasInternetConnection() {
return Single.fromCallable(() -> {
try {
// Connect to Google DNS to check for connection
int timeoutMs = 1500;
Socket socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 53);

socket.connect(socketAddress, timeoutMs);
socket.close();

return true;
} catch (IOException e) {
return false;
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

hasInternetConnection().subscribe((hasInternet) -> {
if(hasInternet) {

}else {

}
});

Extra: One-shot AsyncTask Example

Caution: This shows another example of how to do the request. However, since AsyncTask is deprecated, it should be replaced by your App's thread scheduling, Kotlin Coroutines, Rx, ...

class InternetCheck extends AsyncTask<Void,Void,Boolean> {

private Consumer mConsumer;
public interface Consumer { void accept(Boolean internet); }

public InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }

@Override protected Boolean doInBackground(Void... voids) { try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) { return false; } }

@Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

new InternetCheck(internet -> { /* do something with boolean response */ });

How to detect internet connectivity using java program

It depends on what you mean by "internet" connection. Many computers are not connected directly to the internet, so even if you could check whether they have a network connection, it doesn't always mean they can access the internet.

The only 100% reliable way to test whether the computer can access some other server is to actually try.

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager != null ? connectivityManager.getActiveNetworkInfo() : null;
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.



Related Topics



Leave a reply



Submit