我需要知道连接到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地址已解决此问题。无论如何,感谢所有感兴趣并帮助解决的人。
答案 0 :(得分:1)
如果您的网络也支持IPv6,则应检查两者,而不是
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
使用:
if (ip.Address.AddressFamily == AddressFamily.InterNetwork
|| ip.Address.AddressFamily == AddressFamily.InterNetworkV6)
您可以查看AddressFamily
枚举here on MSDN.