Skip to content

Instantly share code, notes, and snippets.

@russellhoff
Created September 27, 2017 13:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russellhoff/4ee23265c9c93fdea005f03a7a06c96d to your computer and use it in GitHub Desktop.
Save russellhoff/4ee23265c9c93fdea005f03a7a06c96d to your computer and use it in GitHub Desktop.
Check Internet Connection in Java
package internetcon;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class CheckInternet {
public static void main(String[] args) {
System.out.println(
"Online: " +
(testInet("myownsite.example.com") || testInet("google.com") || testInet("amazon.com"))
);
}
public static boolean testInet(String site) {
Socket sock = new Socket();
InetSocketAddress addr = new InetSocketAddress(site,80);
try {
sock.connect(addr,3000);
return true;
} catch (IOException e) {
return false;
} finally {
try {
sock.close();
}catch (IOException e) {
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment