How can I know whether a VPN connection is established or not?
I check the VPN connection status using the NetworkInterface
class. Here is the code I wrote for this goal:
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in interfaces)
{
if (Interface.OperationalStatus == OperationalStatus.Up)
{
if ((Interface.NetworkInterfaceType == NetworkInterfaceType.Ppp) && (Interface.NetworkInterfaceType != NetworkInterfaceType.Loopback))
{
IPv4InterfaceStatistics statistics = Interface.GetIPv4Statistics();
MessageBox.Show(Interface.Name + " " + Interface.NetworkInterfaceType.ToString() + " " + Interface.Description);
}
else
{
MessageBox.Show("VPN Connection is lost!");
}
}
}
}
A slight modification - this is the code that worked for me.
public bool CheckForVPNInterface()
{
if (NetworkInterface.GetIsNetworkAvailable())
{
NetworkInterface[] interfaces =
NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface Interface in interfaces)
{
// This is the OpenVPN driver for windows.
if (Interface.Description.Contains("TAP-Windows Adapter")
&& Interface.OperationalStatus == OperationalStatus.Up)
{
return true;
}
}
}
return false;
}
On my network driver there was Cisco
in the description text. Here is a more up-todate version which is only a few lines:
public static class VPNCheck
{
public static bool IsOn()
{
return ((NetworkInterface.GetIsNetworkAvailable())
&& NetworkInterface.GetAllNetworkInterfaces()
.FirstOrDefault(ni => ni.Description.Contains("Cisco"))?.OperationalStatus == OperationalStatus.Up);
}
}