Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check internet connectivity in Java [duplicate]

Tags:

java

I am working on a Java project which needs to have an internet connection at all times.

I want my program to keep checking the internet connection at some time intervals (say 5 or 10 seconds) and display a message as soon as no internet connection is detected.

I have tried to use the isReachable method to achieve this functionality, below is the code -

try
{
    InetAddress add = InetAddress.getByName("www.google.com");
    if(add.isReachable(3000)) System.out.println("Yes");
    else System.out.println("No");
}
catch (UnknownHostException e) 
{
    System.out.println("unkownhostexception");
} 
catch (IOException e) 
{
    System.out.println("IoException");
}

But this code always returns "No". What is the problem with this code?

Thanks

like image 479
Ankit Rustagi Avatar asked Jun 09 '13 07:06

Ankit Rustagi


2 Answers

I agree with Raffaele's suggestion if you just need to use the internet frequently. Just try to do it, and be prepared to handle the exceptions when it fails.

If you need to monitor the availability of the internet for some reason, even when you don't intend to use it yet and don't know who you'll connect to, just try a connection to a known-good site (google.com, amazon.com, baidu.com... ).

This will work to test a few sites:

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) {}
    }
}
like image 129
maybeWeCouldStealAVan Avatar answered Sep 22 '22 20:09

maybeWeCouldStealAVan


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.

like image 30
Raffaele Avatar answered Sep 20 '22 20:09

Raffaele