【问题标题】:Get the IP address of a machine connected to/in a VPN network获取连接到/在 VPN 网络中的机器的 IP 地址
【发布时间】: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


【解决方案1】:

如果您的网络也支持 IPv6,您应该同时检查两者,而不是

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

使用:

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

你可以看到AddressFamily枚举here on MSDN.的所有值

【讨论】:

    猜你喜欢
    • 2012-11-03
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2022-07-26
    • 2012-09-29
    • 2019-12-11
    • 2011-11-12
    • 2014-04-15
    相关资源
    最近更新 更多