简体   繁体   中英

Checking Internet Connection without URL test connection using java

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 ?

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM