1

How can I check whether my computer is connected to the Internet. I don't want to use URL check method. Is it possible to call an operating system's function using java? For example, in JNA library, is there any function to perform this ?

1
  • Guess how the OS checks your Internet connection... Commented Jun 29, 2014 at 3:41

2 Answers 2

2

You can use ping command like this:

class PingHost 
{
        public static void main(String[] args) 
        {
            String ip = "www.google.com";
            String pingResult = "";

            String pingCmd = "ping " + ip;
            try 
            {
                Runtime r = Runtime.getRuntime();
                Process p = r.exec(pingCmd);

                BufferedReader in = new BufferedReader(new
                InputStreamReader(p.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) 
                {
                    System.out.println(inputLine);
                    pingResult += inputLine;
                }
                in.close();

            } catch (IOException e) {
                System.out.println(e);
            }

        }
    }

You should receive a response like:

64 bytes from 173.194.37.147: icmp_seq=0 ttl=52 time=299.032 ms
64 bytes from 173.194.37.147: icmp_seq=1 ttl=52 time=508.100 ms
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for reply but I am going to use this feature in a Thread. Program should check the connection per second. If I use this kind of method, my program will slow down after a while.
@fivetech You can use ping -c 1 www.google.com. It will stop after receiving the response. Btw, there are many useful commands for ping linux.die.net/man/8/ping. Ping cmd is the best command to check for connection.
Thank you so much. My app works fine. I set Thread.sleep(2000) and it doesn't use system resources much more now.
@fivetech glad to help. Any upvote will appreciated :)
My reputation is not enough to vote up because I am new on this site
|
0

You could check to see if a common hostname (such as google) is resolvable through dns to an ip address.

Once that address has been resolved, you can check to see if it is reachable.

2 Comments

Thanks for reply but isReachable method returns always false. I don't know how to manage this issue. :(
The method basically does the same thing as ping, which many networks have blocked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.