c#知道我们用哪个IP与另一个IP通信?

J4N*_*J4N 4 .net c# network-programming

使用自制的发现工具,我发现了一系列我感兴趣的服务.

我有他们的IP,服务名称,端口,主机......但是为了使用它们,我要向客户端库指定我们将使用的IP.

由于我有几个网卡,我需要检测哪个接口用于与我知道的目标IP通信,然后将其提供IPAddress给我的库.

但是我怎么能检测到我应该使用哪个接口IP?

我试图通过互联网进行一些搜索,但我认为我没有正确的关键字,因为我找不到任何相关的东西.

Mar*_*rcF 7

我已经从我为networkComms.net开发的网络库中为您提取了相关的方法:

/// <summary>
/// Determines the most appropriate local end point to contact the provided remote end point. 
/// Testing shows this method takes on average 1.6ms to return.
/// </summary>
/// <param name="remoteIPEndPoint">The remote end point</param>
/// <returns>The selected local end point</returns>
public static IPEndPoint BestLocalEndPoint(IPEndPoint remoteIPEndPoint)
{    
    Socket testSocket = new Socket(remoteIPEndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
    testSocket.Connect(remoteIPEndPoint);
    return (IPEndPoint)testSocket.LocalEndPoint;
}
Run Code Online (Sandbox Code Playgroud)

获得正确的IP后,您可以迭代NetworkInterface.GetAllNetworkInterfaces()以找到匹配的适配器.