如果要得知遠端的MAC位址應該怎麼做,雖然可以利用arp的指令並將結果輸出到文字檔,但這樣有點麻煩,找了些參考資料後,我們可以用下面的程式碼來取得
要取得本機的MAC位置我們可以利用WMI或是.Net framework提供的相關功能來作,例如下面這兩篇
那如果要得知遠端的MAC位址應該怎麼做,雖然可以利用arp的指令並將結果輸出到文字檔,但這樣有點麻煩,找了些參考資料後,我們可以用下面的程式碼來取得
首先是一些參考資料
下面是測試的程式碼
Private Const No_ERROR = 0
<DLLIMPORT("WSOCK32.DLL", ) EntryPoint:="inet_addr" CharSet:="CharSet.Ansi,"> _
Private Shared Function inet_addr(ByVal s As String) As Integer
End Function
<DLLIMPORT("IPHLPAPI.DLL", ) EntryPoint:="SendARP" CharSet:="CharSet.Ansi,"> _
Private Shared Function SendARP(ByVal DestIp As Integer, _
ByVal ScrIP As Integer, _
ByRef pMacAddr As Long, _
ByRef PhyAddrLen As Long) As Integer
End Function
<DLLIMPORT("KERNEL32.DLL", ) EntryPoint:="RtlMoveMemory" CharSet:="CharSet.Ansi,"> _
Private Shared Sub CopyMemory(ByVal dst As Byte(), ByRef src As Long, ByVal bcount As Integer)
End Sub
Private Function GetRemoteMACAddress(ByVal sRemoteIP As String, ByRef sRemoteMacAddress As String) As Boolean
Dim dwRemoteIp As Integer
Dim pMacAddr As Long = 0
Dim bpMacAddr() As Byte
Dim PhyAddrLen As Long = 0
Dim cnt As Long
Dim tmp As String = ""
dwRemoteIp = inet_addr(sRemoteIP)
If dwRemoteIp <> 0 Then
PhyAddrLen = 6
If SendARP(dwRemoteIp, 0&, pMacAddr, PhyAddrLen) = No_ERROR Then
If pMacAddr <> 0 And PhyAddrLen <> 0 Then
ReDim bpMacAddr(0 To PhyAddrLen - 1)
CopyMemory(bpMacAddr, pMacAddr, PhyAddrLen)
For cnt = 0 To PhyAddrLen - 1
tmp &= Hex(bpMacAddr(cnt) + 256).Substring(1, 2) & "-"
Next
If Len(tmp) > 0 Then
sRemoteMacAddress = tmp.Substring(0, tmp.Length - 1)
GetRemoteMACAddress = True
End If
Exit Function
Else
GetRemoteMACAddress = False
End If
Else
GetRemoteMACAddress = False
End If
Else
GetRemoteMACAddress = False
End If
End Function