- 1 year ago
Using NetworkInterface get current connection name and ip for vpn
To get the current connection name and IP address for a VPN connection using NetworkInterface
in C#, you can loop through all the available network interfaces and check if the interface is a VPN interface. If it is, you can get its connection name and IP address.
Here's a code example that demonstrates how to do this:
csharpusing System;
using System.Net.NetworkInformation;
public class Program
{
public static void Main()
{
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface networkInterface in networkInterfaces)
{
// Check if the network interface is a VPN interface
if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ppp)
{
// Get the connection name
string connectionName = networkInterface.Name;
// Get the IP addresses associated with the interface
IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
foreach (UnicastIPAddressInformation ipAddressInfo in ipProperties.UnicastAddresses)
{
// Check if the IP address is IPv4 and not loopback
if (ipAddressInfo.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork &&
!IPAddress.IsLoopback(ipAddressInfo.Address))
{
string ipAddress = ipAddressInfo.Address.ToString();
Console.WriteLine($"VPN Connection Name: {connectionName}");
Console.WriteLine($"VPN IP Address: {ipAddress}");
break;
}
}
}
}
}
}
In this example, we use NetworkInterface.GetAllNetworkInterfaces()
to retrieve all available network interfaces on the system. Then, we loop through each interface and check if it is a VPN interface by comparing the NetworkInterfaceType
property to NetworkInterfaceType.Ppp
.
If the interface is a VPN interface, we get its connection name from the Name
property. Next, we get the IP addresses associated with the interface using the GetIPProperties
method. We loop through the IP addresses and check if it is an IPv4 address and not a loopback address. If these conditions are met, we print the VPN connection name and IP address to the console.
Keep in mind that this code will only show the current active VPN connection and its IP address. If there are multiple VPN connections, it will only display information for the first one it encounters.