[CODE] Detecting if a VPN connection is active programmatically (Jan/2017)

This method of programatic detection works as of January 24, 2017 with the latest versions of Express VPN and PIA (Private Internet Access)

On Mac OSX/
This works for Mac OSX 10.2.2.

The trick is to request your ip routing table and examine through which network interface your default traffic is going through.
(To do this programmatically you will have to parse the output with your favorite programming language)

This is how it looks for both ExpressVPN and PIA when the VPN is active:

To request your routing table you can do this on the command line:
netstat -nr

Notice the line starting with “0/1”, it’s going through that tunnel interface. (In Linux it would show 0.0.0.0 instead of 0/1)

VPN ON output in Mac

Internet:
Destination        Gateway            Flags        Refs      Use   Netif Expire
0/1                10.81.10.5         UGSc            5        0   utun1
...

VPN ON output in Linux

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         10.31.10.5      128.0.0.0       UG        0 0          0 tun0
...

When you turn VPN off this is how it looks:

VPN OFF in Mac

Destination        Gateway            Flags        Refs      Use   Netif Expire
default            192.168.1.1        UGSc           66        0     en0
127                127.0.0.1          UCS             2        4     lo0

VPN OFF in Linux

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         172.16.245.2    0.0.0.0         UG        0 0          0 eth0

So a quick way to determine if the VPN is on or off in Mac or Linux, is to filter-out what you care for using grep.
If you have any output it’s on, if not it’s off

netstat -nr | egrep "^0" | grep "tun"

(we filter for “tun” and not utun1, as in linux vpn network interfaces start with “tun”)

Parse the output of that command and you will have your VPN status. No output means VPN is disconnected. Some output means the VPN is connected.

On Windows
Do a nestat -nr and look for 128.0.0.1, if you find it, VPN is on.

Leave a Reply

Your email address will not be published. Required fields are marked *