그래서 나는 윈도우 API를 포장하는 것이 가장 지저분한 해결책이 될 것이라고 결정하고 모두가 볼 수 있도록 다음과 같은 내놓았다했습니다
먼저 나는라는 이름의 개인 생성자와 Friend NotInheritable Class
을 만들어 NativeMethods 약 (서브 클래스 (static internal) 인 IPHelper이있는 C#의 정적 내부 클래스와 동일합니다. 이것은 내가 뻔뻔하게 pinvoke.net (source)에서 복사 한 DllImport를 넣는 곳입니다.
Friend NotInheritable Class NativeMethods
Private Sub New()
End Sub
Friend NotInheritable Class IPHelper
Private Sub New()
End Sub
' Possible return values
Friend Const NO_ERROR As Integer = 0
Friend Const ERROR_BAD_NET_NAME As Integer = 67
Friend Const ERROR_BUFFER_OVERFLOW As Integer = 111
Friend Const ERROR_GEN_FAILURE As Integer = 31
Friend Const ERROR_INVALID_PARAMETER As Integer = 87
Friend Const ERROR_INVALID_USER_BUFFER As Integer = 1784
Friend Const ERROR_NOT_FOUND As Integer = 1168
Friend Const ERROR_NOT_SUPPORTED As Integer = 50
' API function declaration.
<DllImport("iphlpapi.dll", SetLastError:=True)>
Friend Shared Function SendARP(
DestIP As UInt32,
SrcIP As UInt32,
pMacAddr() As Byte,
ByRef PhyAddrLen As Int32) As UInt32
End Function
End Class
End Class
지금 그 위에 나는 공용 클래스 SendARP 방법을 소비
ArpRequest을 썼다.
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Imports System.IO
Imports System.Net.NetworkInformation
Public Class ArpRequest
Private _address As IPAddress
Public Sub New(address As IPAddress)
_address = address
End Sub
''' <summary>
''' Gets the MAC address that belongs to the specified IP address.
''' </summary>
''' <remarks>This uses a native method and should be replaced when a managed alternative becomes available.</remarks>
Public Function GetResponse() As PhysicalAddress
Dim ip As UInteger = BitConverter.ToUInt32(_address.GetAddressBytes(), 0)
Dim mac() As Byte = New Byte(5) {}
Dim ReturnValue As Integer = CInt(NativeMethods.IPHelper.SendARP(CUInt(ip), 0, mac, mac.Length))
If ReturnValue = NativeMethods.IPHelper.NO_ERROR Then
Return New PhysicalAddress(mac)
Else
' TODO: handle various SendARP errors
' http://msdn.microsoft.com/en-us/library/windows/desktop/aa366358(v=vs.85).aspx
Throw New Win32Exception(CInt(ReturnValue))
End If
End Function
End Class
사용법은 간단합니다 (그러나 Win32Exceptions 조심) :
Dim ip = System.Net.IPAddress.Parse("0.0.0.0") ' replace with actual ip
Dim arp = New ArpRequest(ip)
Dim hardwareAddress = arp.GetResponse()