主动识别网络接口接口、主动、网络

2023-09-02 21:10:32 作者:╰╮清黎╭╯

在.NET应用程序,我怎么能确定哪个网络接口用来传达给定的IP地址?

In a .NET application, how can I identify which network interface is used to communicate to a given IP address?

我在工作站上使用多个网络接口,IPv4和V6运行,并且我需要得到用于通信的正确的接口的地址,我给数据库服务器。

I am running on workstations with multiple network interfaces, IPv4 and v6, and I need to get the address of the "correct" interface used for traffic to my given database server.

推荐答案

最简单的方法是:

UdpClient u = new UdpClient(remoteAddress, 1);
IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;

现在,如果你想要的NetworkInterface对象,你做这样的事情:

Now, if you want the NetworkInterface object you do something like:


foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
   IPInterfaceProperties ipProps = nic.GetIPProperties();
   // check if localAddr is in ipProps.UnicastAddresses
}

另一种选择是使用的P / Invoke并调用 GetBestInterface()以得到接口索引,然后再次遍历所有的网络接口。和以前一样,你必须通过 GetIPProperties()来掏去了 IPv4InterfaceProperties.Index 属性)。

Another option is to use P/Invoke and call GetBestInterface() to get the interface index, then again loop over all the network interfaces. As before, you'll have to dig through GetIPProperties() to get to the IPv4InterfaceProperties.Index property).