2012-04-27 2 views
1

私はC言語(または他の管理されていない言語でのプログラミング)についての背景はまだありませんが、.NETアプリケーションのIP Helper APIのGetBestInterface関数を使用したいと考えています。私は、P/invoke呼び出しをネイティブメソッドの呼び出しに使用する方法を理解しようとしましたが、管理対象コードの型がアンマネージ型にマップされる方法など、私には分かりません。GetBestInterfaceの管理下の代替手段ですか?

System.Net名前空間に隠された別の機能がありますが、これはほぼ同じことですか?あるいは、私は、既存のベースクラスといくつかの魔法を組み合わせて独自の選択肢を書くことができますか?それは基本的に私のようなものです:魔法です。私はちょうど私が非常に役立つことができると思いSystem.Net.Sockets.SocketクラスにLocalEndPointプロパティを発見した方法は、それは私の知る限り何実現する方法のための本当の説明は...ありません

EDIT

これで私の理解のために、私のために最良のインターフェイス選択を行い、ローカルエンドポイントに対応するNICを取得するだけでよいでしょう。

+0

http://pinvoke.net/:これは、トリックを行います

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 

default.aspx/iphlpapi/GetBestInterface.html –

+0

@HansPassant返すインデックスは無駄です私の能力をはるかに超えているGetAdaptersInfoを探しています。 –

+0

try rentacoder.com –

答えて

1

私は自分自身でインタフェースピッキングを実行するフレームワークの能力にピギーバックすることで動作する何かを自分自身でまとめました。基本的にソケットを接続してから、ソケットのLocalEndPointプロパティを使用して、使用しているNICを取得します。おそらくそれを行うには最高の方法ではないが、それは私のために働く。

使用して、次のimport文:

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

そして、私のスーパー素晴らしい方法:

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