主动识别网络接口 [英] Identifying active network interface

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

问题描述

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆