好吧,我自己整理了一些东西,这些东西通过捎带框架自己进行界面选择的能力来工作。本质上它只是连接一个套接字,然后使用套接字上的 LocalEndPoint 属性来获取它正在使用的 NIC。可能不是最好的方法,但它对我有用。
使用以下导入语句:
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