简体   繁体   中英

How to check internet connection using network device in java?

i need to check internet connection without push URL. how can i check internet connection using interface device or something else. i try using this code but it is not working while internet is not available. please help me.

try {
    Enumeration<NetworkInterface> interfaces;
    interfaces = NetworkInterface.getNetworkInterfaces();
    while(interfaces.hasMoreElements()) {
        NetworkInterface iface = interfaces.nextElement();
        if (iface.isUp() && !iface.isLoopback()) {
            JOptionPane.showMessageDialog(null, "connect");

        }
    }
}
catch(Exception e) {
    JOptionPane.showMessageDialog(null, "connect first");
}    

check this example without pushing url:

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class CheckInternetConnection{

    public static void main(String[] args){

        Enumeration<NetworkInterface> interfaces = null;

        try {   
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }  
        while (interfaces.hasMoreElements()) {  
            NetworkInterface nic = interfaces.nextElement();   
            System.out.print("Interface Name : [" + nic.getDisplayName() + "]");     
            try {    
                 System.out.println(", is connected : [" + nic.isUp() + "]"); 
            } catch (SocketException e) {
                e.printStackTrace();
            }  
        }   
    }
}

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