views:

121

answers:

2

I want to be able to detect when a computer connects to a network. The environment is Java 5 under Windows.

+2  A: 

I think your choices are to either use some JNI library (though I'm not familiar with one offhand and that would tend to be platform specific), or just try making a network connection to some known IP (google for example). Neither solution is elegant, but I don't believe there is a pure Java API in 1.5 for determining this.

In Java 1.6, you could use java.net.NetworkInterface.isUp(), but obviously that won't help for your case of using 1.5.

jsight
this may be a good reason to upgrade to 1.6
Joshua
A: 

maybe check in a thread?

try {
  InetAddress inetAddr = InetAddress.getByName(host);
  setOnline();
} catch (UnknownHostException e) {
  setOffline();
}
Willi aus Rohr
yes, that would basically work. Albeit you have to either turn off DNS caching or vary the host that you lookup. And depending on your specific requirements, this could show a "false" disconnect just b/c of DNS server issues. I think connecting by IP to a known address might be marginally better.
jsight