よし、自分でインターフェース選択を行うフレームワークの機能に便乗することで機能するものを自分でまとめました。基本的に、ソケットを接続し、ソケットの 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