2

私は C (またはその他のアンマネージ言語) でのプログラミングの経験はまったくありませんが、.NET アプリケーションで IP Helper APIのGetBestInterface関数を使用したいと考えています。P/invoke 呼び出しを使用してネイティブ メソッドを呼び出す方法を理解しようとしましたが、理解できないことがたくさんあります (マネージド コードの型がアンマネージド型にどのようにマップされるかなど)。

ほぼ同じことを行う System.Net 名前空間のどこかに隠された代替機能はありますか? または、既存の基本クラスをいくつかの魔法と組み合わせて使用​​して、独自の代替手段を作成できますか? それが基本的に私には見えるものだからです:魔法. 私が知る限り、メソッドがどのように機能するかについての実際の説明はありません...

編集

System.Net.Sockets.Socketこれで非常に役立つと思われるクラスの LocalEndPoint プロパティを発見しました。私の理解では、それは私に代わって最適なインターフェイスの選択を行い、ローカル エンドポイントに対応する NIC を取得するだけで済みます。

4

2 に答える 2

1

よし、自分でインターフェース選択を行うフレームワークの機能に便乗することで機能するものを自分でまとめました。基本的に、ソケットを接続し、ソケットの LocalEndPoint プロパティを使用して、使用している NIC を取得します。おそらくそれを行うための最良の方法ではありませんが、私にとってはうまくいきます。

次の import ステートメントを使用します。

Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets

そして私の超素晴らしい方法:

Private Function GetBestInterfaceManaged(ByVal address As IPAddress, ByVal port As Integer) As NetworkInterface

    Dim socket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
    Dim outgoingInterface As NetworkInterface = Nothing

    Try
        socket.Connect(New IPEndPoint(address, port))

        If socket.Connected Then ' find the outgoing NIC

            Dim interfaces As List(Of NetworkInterface) = NetworkInterface.GetAllNetworkInterfaces.ToList()

            For Each nic As NetworkInterface In interfaces
                Dim properties As IPInterfaceProperties = nic.GetIPProperties

                For Each unicastAddress In properties.UnicastAddresses
                    If unicastAddress.Address.Equals(DirectCast(socket.LocalEndPoint, IPEndPoint).Address) Then
                        outgoingInterface = nic
                    End If
                Next
            Next

            If outgoingInterface Is Nothing Then
                Console.WriteLine("Darn... it didn't work!")
            Else
                Console.WriteLine("Outgoing interface: {0}", outgoingInterface.Name)
            End If

            Return outgoingInterface
        End If
    Catch ex As SocketException
        Console.WriteLine(ex.Message)
    End Try
    Return Nothing
End Function

これはトリックを行います:

Sub Main()
    Dim hostEntry As IPHostEntry = Dns.GetHostEntry("www.stackoverflow.com")
    Dim NIC As NetworkInterface = GetBestInterfaceManaged(hostEntry.AddressList.First, 80)
    ' Other code goes down here
End Sub
于 2012-04-28T10:57:16.813 に答える