2012-04-27 2 views
1

C 프로그래밍에 대한 배경 지식이 없지만 .NET 응용 프로그램의 IP Helper API에서 GetBestInterface 함수를 사용하고 싶습니다. P/invoke 호출을 사용하여 네이티브 메소드를 호출하는 방법을 이해하려고 시도했지만, 관리되지 않는 유형에 대한 관리되는 코드 맵의 유형과 같은 저에게 의미가없는 많은 것들이 있습니다.GetBestInterface 용 관리 대안?

System.Net 네임 스페이스에 대체로 동일한 기능을 숨기는 다른 기능이 있습니까? 아니면 기존의 기본 클래스와 마법을 조합하여 내 자신 만의 대안을 쓸 수 있을까요? 그게 기본적으로 나에게 보이는 것 : 마술. 난 그냥 매우 유용 할 수있다 생각 System.Net.Sockets.Socket 클래스의 LocalEndPoint 속성을 발견

방법은 그것까지 내가 말할 수있는 무엇을 수행하는 방법에 대한 실제 설명 ...

편집은 없다 이걸로. 내 이해를 위해 필자를 대신하여 최상의 인터페이스 선택을 할 것이며 로컬 끝점에 해당하는 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