获取连接到VPN网络的机器的IP地址

本文关键字:机器 地址 IP 网络 连接 VPN 获取 | 更新日期: 2023-09-27 18:18:02

我需要知道连接到VPN的机器的IP地址。我使用了以下算法:

if (NetworkInterface.GetIsNetworkAvailable()) { // First check if any connections are present
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
bool vpnExists=false;
string ipAddr="?";
foreach (NetworkInterface Interface in interfaces)
{ // Loop through all interfaces present
    if (Interface.OperationalStatus == OperationalStatus.Up)
    { // consider only if an interface is currently active
        if (Interface.NetworkInterfaceType == NetworkInterfaceType.Tunnel) // refering to vpn
        { // vpn found              
            vpnExists=true;
            foreach (UnicastIPAddressInformation ip in Interface.GetIPProperties().UnicastAddresses) { 
                // Program control reaches here without any problem
                if (ip.Address.AddressFamily==AddressFamily.InterNetwork) { // this block does not execute as expected
                    ipAddr=ip.Address.ToString();
                }
            }
        }
        else
        { // vpn not found
            continue; // Goto another interface
        }
    }
  }             
}
/*
Final state of variables:
   vpnExists: true
   ipAddr: "?"
*/

代码功能完美,直到VPN检查部分(对于我尝试过的所有网络),但不显示VPN检测后的IP地址。我不明白为什么语句(ip.Address.AddressFamily==AddressFamily.InterNetwork)返回false,因为我相信这是获得IP地址的正确方式。

谁能指出为什么会发生这种情况?一个深入的解释也会很有帮助。

提前感谢。

更新:通过手动映射IP地址可以解决该问题。无论如何,感谢所有关心并帮助解决问题的人。

获取连接到VPN网络的机器的IP地址

如果你的网络也支持IPv6,你应该检查两者,即,而不是

if (ip.Address.AddressFamily == AddressFamily.InterNetwork)

使用:

if (ip.Address.AddressFamily == AddressFamily.InterNetwork
 || ip.Address.AddressFamily == AddressFamily.InterNetworkV6)

您可以在MSDN上看到AddressFamily枚举的所有值。