Search code examples
javaconnectionjna

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 ?


Solution

  • 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