Search code examples
windowsnetwork-programmingvpnnetwork-interfacevirtual-network-interface

How to get the underlying network interface used by a VPN connection in Windows


The closest thing to a solution I've found is using Get-NetConnectionProfile to return all active interfaces, which works fine when there's only an active physical interface and the VPN itself. However, this would not work if the user's machine has 2 active physical interfaces (e.g Wi-Fi + Ethernet) along with the VPN.

Get-NetConnectionProfile

Ideally, I'd like a solution that works similarly to "ifconfig -v" in MacOS, which tells you the effective interface for a virtual interface:

ifconfig -v


Solution

  • Unfortunately it seems there is no sure-fire way to get the underlying physical adapter for a VPN using a Windows API. Short of involving a packet sniffer such as Wireshark, the best solution I found involves parsing the output of two PowerShell commands: Get-NetAdapter and Get-NetRoute.

    With the information from these commands, I can know which interfaces are virtual and which ones are physical, and I can rank the physical interfaces by 3 different criteria (in case of tie, we move on to the next criteria):

    1. Sorting the physical interfaces by the interface metric + the route metric to the default gateway (0.0.0.0).

    2. Wired connections over wireless ones (PhysicalMediaType=802.3).

    3. Prioritizing faster adapters.

    With this logic all the VPNs I tested appear to reflect the expected network interface, although some VPNs let you force traffic through a particular physical adapter in which case obviously this all goes out the window.