Java Internet connection checker

Over a year ago Anand Sreenivasan published a short Java class which purpose was to check for Internet connectivity on the computer of the person running it. It was meant to be used as a CLI app. I decided to make it a little bit more reusable.

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.CharBuffer;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class InternetChecker {
 
	private static final String URL_TO_CHECK = "http://www.google.com/";
	private static final long CHECK_EVERY = 30 * 60 * 1000; /* 30 minutes */
 
	private static final int BUF_SIZE = 1024;
	private static InternetChecker ref;
	private Date lastCheck;
	private Boolean lastState;
	private final Logger log = Logger.getLogger(InternetChecker.class.getName());
 
	public InternetChecker() {
	}
 
	private boolean isStateValid() {
		if (lastState == null)
			return false;
		if (lastCheck.getTime() > System.currentTimeMillis() + CHECK_EVERY)
			return false;
		return true;
	}
 
	public boolean isConnectionPresent() {
		if (!isStateValid()) {
			checkConnection();
		}
		return lastState;
	}
 
	public boolean isConnectionPresent(boolean forceCheck) {
		if (forceCheck)
			invalidateState();
		return isConnectionPresent();
	}
 
	private void invalidateState() {
		lastCheck = null;
		lastState = null;
	}
 
	public void checkConnection() {
		lastCheck = new Date();
		try {
			URL url = new URL(URL_TO_CHECK);
			URLConnection urlConnection = url.openConnection();
 
			InputStream inputStream = urlConnection.getInputStream();
			Reader reader = new InputStreamReader(inputStream);
 
			StringBuilder contents = new StringBuilder();
			CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
 
			while (true) {
				reader.read(buf);
				if (!buf.hasRemaining())
					break;
 
				contents = contents.append(buf);
			}
			inputStream.close();
			lastState = true;
			log.log(Level.INFO, "Internet connectivy present.");
		} catch (Exception e) {
			log.log(Level.WARNING, "Internet connectivity not present.", e);
			lastState = false;
		}
	}
 
	public static InternetChecker getDefaultInstance() {
		if (ref == null) {
			ref = new InternetChecker();
		}
		return ref;
	}
}

To use it you invoke:

InternetChecker.getDefaultInstance().isConnectionPresent();

You can also force checking the connection by passing true to the isConnectionPresent() method.

Please to report any bugs or ideas, I will update the class if necessary.

Tags:

3 Responses to “Java Internet connection checker”

  1. Bhavik says:

    Nice post man.
    We can use listener pattern with this code to
    fire connection status change to its listeners.

  2. jnewb says:

    I need help, how to keep this running.. Mine only runs once when I start my program.

    I decreased time to 1 * 60 * 1000

    That should run every minute.

    I’m just learning JAVA ..

    thanks

  3. Andrzej says:

    The method getDefaultInstance is not thread-safe. It should synchronized.

    public synchronized static InternetChecker getDefaultInstance() {
    if (ref == null) {
    ref = new InternetChecker();
    }
    return ref;
    }

    Now it’s true Singleton :)

Leave a Reply