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(
             byref(flags),
             None,
             )
if not connected:
   print ' [!] No internet connection, cannot retrieve data'
else:
   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 ;)

Example:

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.

Links:

  • InternetGetConnectedState Function –> HERE

2 Responses to {Quick Post} More fun with Python ctypes – InternetConnectedState

  1. Pingback: Yet more fun with Python ctypes – SSPI « Cатсн²² (in)sесuяitу / ChrisJohnRiley

  2. Pingback: What, more Python ctypes! – DNS TXT records « Cатсн²² (in)sесuяitу / ChrisJohnRiley

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 36 other followers