【发布时间】:2016-11-15 10:29:52
【问题描述】:
我需要知道连接到 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 地址得到解决。无论如何,感谢所有感兴趣并帮助解决的人。
【问题讨论】:
-
什么是 ip.Address.AddressFamily?调试你的代码
-
@TheLethalCoder 我正在检查地址的寻址方案。它有什么问题?抱歉回复晚了。
-
当你到达你期望为真的 if 语句评估为假时,
ip.Address.AddressFamily的值是什么? -
@TheLetalCoder 该值为“InterNetworkV6”。它应该只是'InterNetwork',不是吗? (因为我只使用 IPv4 而不是 v6)
标签: c# network-programming ip-address vpn