Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if a network card is not connected with Java without delay?

It there an API (NetworkInterface, InetAddress, etc) in Java with which I can detect that a network card is not connected.

The problem is that addressing some of the network API has a large timeout. But if the network card is not connected to any cable then we can skip it. The problem seems only to occur with Windows 7.

like image 807
Horcrux7 Avatar asked Aug 19 '11 13:08

Horcrux7


2 Answers

I had this same problem. I ended up using this:

Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
        while(eni.hasMoreElements()) {
            Enumeration<InetAddress> eia = eni.nextElement().getInetAddresses();
            while(eia.hasMoreElements()) {
                InetAddress ia = eia.nextElement();
                if (!ia.isAnyLocalAddress() && !ia.isLoopbackAddress() && !ia.isSiteLocalAddress()) {
                    if (!ia.getHostName().equals(ia.getHostAddress()))
                        return true;
                }
            }
        }

Works with Java 5+. Also indirectly checks DNS (by comparing names/addresses).

like image 174
BenCole Avatar answered Oct 01 '22 21:10

BenCole


You could use some java system properties to set up the default time out for socket connection using

sun.net.client.defaultConnectTimeout

(all properties here)

But it seems to me that checking wether a specific Medium Access Controller is present or not is the job of the underlying OS. I can't tell you much about windows 7, I got a good OS since 12 years now (linux).

Regards, Stéphane

like image 39
Snicolas Avatar answered Oct 01 '22 22:10

Snicolas