IP routing table lookup in .net

喜夏-厌秋 提交于 2019-12-19 04:09:55

问题


I have a multi-homed machine and need to answer this question:

Given an IP address of the remote machine, which local interface is appropriate to use for communication.

This needs to be done in C#. I can do this query using Win32 Socket and SIO_ROUTING_INTERFACE_QUERY but looking around in the .net framework documentation I haven't found an equivalent for it.


回答1:


I didn't know about this, so just had a look in the Visual Studio Object browser, and it looks like you can do this from the System.Net.Sockets namespace.

In that namespace is a Socket class which contains a method IOControl. One of the overloads for this method takes an IOControlCode (enum in the same namespace) which contains an entry for `RoutingInterfaceQuery'.

I'll try and put some code together as an example now.




回答2:


Someone was nice enough to writez the code, see https://searchcode.com/codesearch/view/7464800/

private static IPEndPoint QueryRoutingInterface(
          Socket socket,
          IPEndPoint remoteEndPoint)
{
    SocketAddress address = remoteEndPoint.Serialize();

    byte[] remoteAddrBytes = new byte[address.Size];
    for (int i = 0; i < address.Size; i++) {
        remoteAddrBytes[i] = address[i];
    }

    byte[] outBytes = new byte[remoteAddrBytes.Length];
    socket.IOControl(
                IOControlCode.RoutingInterfaceQuery, 
                remoteAddrBytes, 
                outBytes);
    for (int i = 0; i < address.Size; i++) {
        address[i] = outBytes[i];
    }

    EndPoint ep = remoteEndPoint.Create(address);
    return (IPEndPoint)ep;
}

which is used like (example!):

IPAddress remoteIp = IPAddress.Parse("192.168.1.55");
IpEndPoint remoteEndPoint = new IPEndPoint(remoteIp, 0);
Socket socket = new Socket(
                      AddressFamily.InterNetwork, 
                      SocketType.Dgram, 
                      ProtocolType.Udp);
IPEndPoint localEndPoint = QueryRoutingInterface(socket, remoteEndPoint );
Console.WriteLine("Local EndPoint is: {0}", localEndPoint);

Please note that although one is specifying an IpEndPoint with a Port, the port is irrelevant. Also, the returned IpEndPoint.Port is always 0.



来源:https://stackoverflow.com/questions/15625023/ip-routing-table-lookup-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!