前段时间,搞个小程序要用到,就综合网上的自己改写了一段,很简单,自己看看吧。
生效范围只有在局域网中,原因很简单,因为在广域网上是无法获知远端的MAC地址的,因为在数据包中的数据链路层包含的只是近端路由器的MAC地址,而你的数据包在互联网上传播,早经过了无数路由器,最后到达你这里的数据包中,只含有最后一个路由器的MAC地址,也就是离你最近的那台路由器。
Private Declare Function inet_addr Lib "wsock32.dll" (ByVal s As String) As Long
Private Declare Function SendARP Lib "iphlpapi.dll" (ByVal DestIP As Long, ByVal SrcIP As Long, pMacAddr As Long, PhyAddrLen As Long) As Long
Private Declare Sub CopyMemory1 Lib "kernel32" Alias "RtlMoveMemory" (dst As Any, src As Any, ByVal bcount As Long)
Public Function GetRemoteMACAddress(ByVal sRemoteIP As String) As String
'VB 获取局域网中指定IP地址的 Mac 地址
Dim dwRemoteIP As Long, pMacAddr As Long, bpMacAddr() As Byte, PhyAddrLen As Long, cnt As Long, tmp As String
dwRemoteIP = inet_addr(sRemoteIP)
If dwRemoteIP <> 0 Then
PhyAddrLen = 6
'On Error Resume Next
If SendARP(dwRemoteIP, 0&, pMacAddr, PhyAddrLen) = 0 Then
If pMacAddr <> 0 And PhyAddrLen <> 0 Then
ReDim bpMacAddr(0 To PhyAddrLen - 1)
CopyMemory1 bpMacAddr(0), pMacAddr, ByVal PhyAddrLen
For cnt = 0 To PhyAddrLen - 1
If bpMacAddr(cnt) = 0 Then
tmp = tmp & "00-"
Else
If Len(Hex$(bpMacAddr(cnt))) = 1 Then
tmp = tmp & "0" & Hex$(bpMacAddr(cnt)) & "-"
Else
tmp = tmp & Hex$(bpMacAddr(cnt)) & "-"
End If
End If
Next
If Len(tmp) > 0 Then
GetRemoteMACAddress = Left$(tmp, Len(tmp) - 1)
End If
Exit Function
Else
GetRemoteMACAddress = "00-00-00-00-00-00"
End If
Else
GetRemoteMACAddress = "00-00-00-00-00-00"
End If 'SendARP
Else
GetRemoteMACAddress = "00-00-00-00-00-00"
End If 'dwRemoteIP
End Function