2013-03-25 95 views
3

我有一個多宿主機器,需要回答這個問題:IP路由表查找.net

給定遠程機器的IP地址,哪個本地接口適合用於通信。

這需要在C#中完成。我可以使用Win32套接字和SIO_ROUTING_INTERFACE_QUERY來做這個查詢,但是在.net框架文檔中查找我還沒有找到它的等價物。

+0

我還沒有設法得到一個套接字工作提供路由表,但這可能讓你開始(如果你需要在正確的方向點) - http://www.winsocketdotnetworkprogramming.com/ – 2013-03-26 22:35:35

回答

1

我不知道這個,所以只需看一下Visual Studio Object瀏覽器,它看起來像你可以從System.Net.Sockets命名空間這樣做。

在該名稱空間中是一個Socket類,其中包含方法IOControl。此方法的重載之一需要IOControlCode(枚舉在同一個命名空間中),其中包含「RoutingInterfaceQuery」的條目。

我現在試着將一些代碼作爲一個例子。

+0

謝謝 - 應該這樣做。 – 2013-03-25 21:43:32

+1

這個例子會有很大的幫助;-) – BatteryBackupUnit 2014-08-27 09:33:07

2

有人不夠好,writez代碼,看看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; 
} 
這是用來像

(例子):

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); 

請注意,雖然一個與端口指定IpEndPoint ,港口是無關緊要的。此外,返回的IpEndPoint.Port始終爲0