To see if a machine is connected to the internet using Java, try pinging a reputable and accessible host, such as Google’s public DNS server (8.8.8.8) and seeing if you receive a response. Here is a basic example:
import java.io.IOException;
import java.net.InetAddress;
public class Main {
public static void main(final String[] args) {
// Prints true if internet is available
// false otherwise
System.out.println(isInternetAvailable());
}
public static boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("8.8.8.8");
return address.isReachable(5000); // Timeout in milliseconds
} catch (IOException e) {
return false;
}
}
}
In the above example, the isInternetAvailable() method attempts to create an InetAddress object using the provided IP address (8.8.8.8). Then, it checks if the address is reachable within a timeout period of 5000 milliseconds (5 seconds) using the isReachable() method. If the address is reachable, it indicates that the computer is connected to the internet.
That was all I had to share with you guys. If you found this code informative and would love to see more, don’t forget to subscribe to our newsletter!