How to detect internet connection using java program

How to write a java program that will tell me if I have Internet access or not. I do not want to ping or create a connection with any external URL, because if this server is unavailable, my program will not work. I want a reliable detection method that will tell me that 100% guarantees that I have an Internet connection or not, regardless of my operating system. I want a program for computers that are directly connected to the Internet.

I tried using the following program

URL url = new URL("http://www.xyz.com/");           
        URLConnection conn = url.openConnection();
        conn.connect();

I want something more suitable than this program

Thanks Sunil Kumar Sahoo

+3
source share
6

, "". , , , , .

100% , .

+4

( , -) , , , , - .. , .

- ... . (, , , , .)

@codeka: " 100% , , - ".

+1

, HTTP :

  • www.google.com
  • www.microsoft.com
  • www.ibm.com
  • www.ford.com

, . , , .

, , : -)

, , - DNS-, , , , .

+1

try/catch . /, .

boolean connectivity;
try {
    URL url = new URL("http://www.xyz.com/");
    URLConnection conn = url.openConnection();
    conn.connect();
    connectivity = true;
} catch (Exception e) {
    connectivity = false;
}

, .

+1
Enumaration<NetworkInterface> networkInterface = null; 

networkInterface = NetworkInterface.getNetworkInterfaces();

for(NetworkInterface interface : Collections.list(networkInterface)){

    System.out.println("Internet Available status is :"+ interface.isUp());

}
0

You can test the connection by setting the class’s Internet protocol InetAddress. If you get an exception or, for example, use getLocalHost()one that returns the local host address, give the following result: localhost/127.0.0.1instead of a full name, for example, for example jaf-stephen-lenovoG40-80/152.6.44.13, then you are not connected to the Internet.

public static void main(String[] args) {
   try {
      InetAddress address = InetAddress.getByName("www.facebook.com");
      System.out.println(address);
   } catch (UnknownHostException e) {
      System.err.println("Couldn't find www.facebook.com");
   }
}

if you are connected to the Internet, you will receive the following output:

www.facebook.com/31.13.78.35

0
source

Source: https://habr.com/ru/post/1736423/


All Articles