Cатсн²² (in)sесuяitу / ChrisJohnRiley

Because we're damned if we do, and we're damned if we don't!

{Quick Post} More fun with Python ctypes – InternetConnectedState

As a followup to my simpleicmp ctypes post, I thought I’d post something about the wininet InternetGetConnectedState function for checking if the network connection is up.

Obviously you can go through the process of sending an icmp echo request and checking if there’s a response, but this is a lot simpler and cleaner (also less prone to issues if echo request are blocked, or the host just doesn’t respond to them). There may also be situations where your script is trying to be as quiet as possible on the network, and firing off random packets to see if the network is up is bad form.

Here’s a simple script that will tell you if the network connection is up or not.

# !/usr/bin/python
# -*- coding: utf-8 -*-

from ctypes import *
from ctypes.wintypes import DWORD

wininet = windll.wininet
flags = DWORD()
connected = wininet.InternetGetConnectedState(
if not connected:
   print ' [!] No internet connection, cannot retrieve data'
   print ' [>] Connection check confirmed'

Again, this is only a small cog in the machine, but I thought it was worth documenting here if only to stop me from forgetting it next time I need to use it 😉


As you can see, this method checks the connection of the network by checking the status of the network port and not by sending anything across the wire.


  • InternetGetConnectedState Function –> HERE
%d bloggers like this: