4

Is there any way to be notified by windows OS when a new connection is available, in a Java program (using JNI)? At the moment the only way I have to check this is by polling a function that tries to download a webpage. If the download success and no exception is thrown, then I can guess there is Internet connectivity.

However, a better solution could be this one:

  1. On program start, check Internet connectivity
  2. If no internet connection is available, "register" for windows network notification and WAIT()
  3. User connects to Internet, Windows os notifies the Java machine=> the threads wakes up
  4. Do some stuff....
Mat
  • 202,337
  • 40
  • 393
  • 406
Alberto Geniola
  • 145
  • 2
  • 8
  • 1
    Seems related to [Notification of when a network interface is ready on Windows](http://stackoverflow.com/q/4546878/291641) although that is not Java. The [WM_DEVICECHANGE](http://msdn.microsoft.com/en-us/library/windows/desktop/aa363480(v=vs.85).aspx) message would also seem a likely candidate for having the system notify you about this. – patthoyts Oct 28 '12 at 08:56
  • Yes, but how to listen to windows messages? I bet there is some JNI library for do that... – Alberto Geniola Dec 24 '12 at 10:04

1 Answers1

0

The following do a ping, less costly than downloading a page, and you can change the time out:

InetAddress.getByName( "stackoverflow.com" ).isReachable( 4000 )

Placed into a thread loop, at low priority:

while( ! InetAddress.getByName( "stackoverflow.com" ).isReachable( 4000 )) {
   Thread.slepp( 1000L );
}

I haven't better.

InetAddress.isReachable documentation:

Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

Aubin
  • 14,617
  • 9
  • 61
  • 84