vb.net - GetBestInterface 的托管替代方案?

标签 vb.net native-code iphelper

我完全没有 C 语言(或任何其他非托管语言)编程的背景,但我想使用 GetBestInterface从我的 .NET 应用程序中的 IP Helper API 运行。我试图了解如何使用 P/invoke 调用来调用 native 方法,但有很多事情对我来说没有意义(例如托管代码中的类型如何映射到非托管类型)。

在 System.Net 命名空间的某个地方是否隐藏了一个替代函数,它做的事情大致相同?或者我可以使用现有的基类结合一些魔法来编写我自己的替代方案吗?因为在我看来,这基本上就是:魔法。据我所知,没有关于该方法如何完成它所做的事情的真正解释......

编辑

我刚刚在 System.Net.Sockets.Socket 类中发现了 LocalEndPoint 属性,我认为它在这方面非常有用。据我了解,它将代表我进行最佳接口(interface)选择,我只需要获取与本地端点对应的 NIC。

最佳答案

我还需要 GetBestInterface因为我需要一个解决方案,如果无法访问要探测的远程地址(Steven 的解决方案会有问题),并且要与我移植到 C# 的 native 应用程序 100% 兼容。

幸运的是,您不必移植 GetAdaptersInfo以及所有相应的 IP_ADAPTER_INFO和子结构 clutter 以查找哪个网络接口(interface)具有 GetBestInterface 返回的索引,因为 .NET can retrieve that index from interfaces too已经。

所以,首先移植GetBestInterface方法如下:

[DllImport("iphlpapi")]
private static extern int GetBestInterface(uint dwDestAddr, ref uint pdwBestIfIndex);

然后,编写一个包装函数如下:

private static NetworkInterface GetBestNetworkInterface(IPAddress remoteAddress)
{
    // Get the index of the interface with the best route to the remote address.
    uint dwDestAddr = BitConverter.ToUInt32(remoteAddress.GetAddressBytes());
    uint dwBestIfIndex = 0;
    uint result = GetBestInterface(dwDestAddr, ref dwBestIfIndex);
    if (result != 0)
        throw new NetworkInformationException((int)result);

    // Find a matching .NET interface object with the given index.
    foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
        if (networkInterface.GetIPProperties().GetIPv4Properties().Index == dwBestIfIndex)
            return networkInterface;

    throw new InvalidOperationException($"Could not find best interface for {remoteAddress}.");
}

然后您可以像这样简单地调用该方法 - 不要忘记无法访问的主机现在也可以工作:

NetworkInterface bestNetworkInterface = GetBestNetworkInterface(IPAddress.Parse("8.8.8.8"));

关于vb.net - GetBestInterface 的托管替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359303/

相关文章:

android - 如何在android 2.1上从sd卡加载jni?

javascript - 从后面的代码关闭弹出窗口

vb.net - 双击 DataGridView 行?

java - 从 Java 获取 native 动态库文件扩展名

c# - 将 .NET 程序集编译成 x86 机器码

c# - 查看 Excel 是否处于 .NET 中的单元格编辑模式的解决方法

.net - VB.NET代码: “Argument not specified for parameter” 中的错误

c++ - DeleteIPAddress 函数有效,但会触发断开连接

interface - 适配器和网络接口(interface)有什么区别?