Determining if a client PC has an Internet connection

Dave Brueck dave at
Mon Sep 20 16:27:06 CEST 2004

Cliff Wells wrote:
> I'm writing an application that needs to know if an Internet connection
> is available.
> Is there any way to reliably determine the state of the client's
> internet connectivity?

Hi Cliff,

On a Win32 system you can reliably determine the state of the Internet 
connection but it requires a fair amount of work. Here's the recipe I use:

1) If the user has a modem and is connected via a modem, you know for sure that 
the user is online (use ctypes to call rasapi32.RasEnumEntriesA to see if the 
user has a modem, and rasapi32.RasEnumConnectionsA to see if the user is 
connected via a modem)

2) If that test fails, next check for open connections to remote hosts. If there 
are any open connections to public IP addresses, the user is "online". (use 
iphlpapi.GetTcpTable to get a list of connections, and keep only those where 
dwState is MIB_TCP_STATE_ESTAB. Remove any addresses that are, 10.*, 
192.168.*, or 172.16-31.*). If after all this the list is non-empty, you're 
probably online.

3) Still no luck? Call IcmpSendEcho to a well-known server - this sends a "ping" 
packet, which won't bring up the dial-up networking box to annoy your users. I 
usually start with a list of all the DNS root servers as well as pingable 
company IP addresses, and randomly choose one of them. Then, anytime I make a 
connection to the Internet, I save the results of the hostname lookup and use 
them in my list as well (so that very few pings actually go to the DNS root 
servers). Also, it's good to make sure that your code has restrictions in place 
to prevent it from pinging anything too often. Due to instant messengers & email 
clients, step #2 usually detects when the user is online, so the need for an 
actual ping is greatly reduced.

Anyway, after doing the above you know with a high degree of certainty whether 
or not the user is online.

The above approach is obviously a lot of work, but once you take the time to do 
it you can just stick it in a library somewhere and not have to think about it 
again. On import of the library, I start up a background thread that updates a 
status variable every second or so, so that any time my app can query to see the 
state of the Internet connection. Although it's a lot of work, I've found that 
(1) it's pretty accurate and (2) it's non-intrusive (it doesn't e.g. pop up the 
dial-up networking dialog box if the user is offline).

Hope at least some of this helps,

More information about the Python-list mailing list