Created
September 27, 2017 13:51
-
-
Save russellhoff/4ee23265c9c93fdea005f03a7a06c96d to your computer and use it in GitHub Desktop.
Check Internet Connection in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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