本文介绍了识别活动网络接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .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).

这篇关于识别活动网络接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:29