只接上代码.大家都看得明白的,(VB.net),函数中的内容理解不了没关系,牛人多的是,咱们只要会用就行啦!
- Imports System.Diagnostics
- Partial Class Other_MAC
- Inherits System.Web.UI.Page
- Private Declare Ansi Function SendARP Lib "Iphlpapi.dll" (ByVal dest As Int32, ByVal host As Int32, ByRef mac As Int64, ByRef length As Int32) As Int32
- Private Declare Ansi Function inet_addr Lib "Ws2_32.dll" (ByVal IP As String) As Int32
- ''' <summary>
- ''' 用于得到MAC地址,速度快,但无法跨VLAN.
- ''' </summary>
- ''' <param name="RemoteIp"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Function GetMAC(ByVal RemoteIp As String) As String
- Dim Dest As Int32 = inet_addr(RemoteIp)
- Dim Str As String = String.Empty
- Dim StrMac As String = String.Empty
- Try
- Dim MacInfo As New Int64
- Dim Len As Int32 = 6
- Dim Res As Integer = SendARP(Dest, 0, MacInfo, Len)
- Str = Convert.ToString(MacInfo, 16).ToUpper
- If Str.Length = 12 Then
- Dim M(5) As String
- M(0) = Str.Substring(10, 2)
- M(1) = Str.Substring(8, 2)
- M(2) = Str.Substring(6, 2)
- M(3) = Str.Substring(4, 2)
- M(4) = Str.Substring(2, 2)
- M(5) = Str.Substring(0, 2)
- StrMac = String.Format("{0}-{1}-{2}-{3}-{4}-{5}", M(0), M(1), M(2), M(3), M(4), M(5))
- Else
- StrMac = "没有查询到MAC."
- End If
- Catch ex As Exception
- Return String.Format("Get Error. 原因:{0}", ex.Message)
- End Try
- Return StrMac
- End Function
- ''' <summary>
- ''' 用于得到MAC地址,速度慢,可以跨VLAN取得MAC地址
- ''' </summary>
- ''' <param name="IP">IP地址</param>
- ''' <param name="name">无意义,任何字符串值</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Private Function GetMac(ByVal IP As String, ByVal name As String) As String
- Dim dirResults As String = ""
- Dim psi As New ProcessStartInfo()
- Dim proc As New Process()
- psi.FileName = "nbtstat"
- psi.RedirectStandardInput = False
- psi.RedirectStandardOutput = True
- psi.Arguments = "-A " & IP
- psi.UseShellExecute = False
- proc = Process.Start(psi)
- dirResults = proc.StandardOutput.ReadToEnd()
- proc.WaitForExit()
- dirResults = dirResults.Replace(vbCr, "").Replace(vbLf, "").Replace(vbTab, "")
- Dim reg As New Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?<key>((.)*?))__MAC", RegexOptions.IgnoreCase Or RegexOptions.Compiled)
- Dim mc As Match = reg.Match(dirResults & "__MAC")
- If mc.Success Then
- Return mc.Groups("key").Value
- Else
- reg = New Regex("Host not found", RegexOptions.IgnoreCase Or RegexOptions.Compiled)
- mc = reg.Match(dirResults)
- If mc.Success Then
- Return "Host not found!"
- Else
- Return ""
- End If
- End If
- End Function
- '在事件中使用
- txt_mac.Text = GetMAC(txt_ip.Text)
- If Trim(txt_mac.Text) = "没有查询到MAC." Then
- txt_mac.Text = GetMAC((txt_ip.Text), "XX")
- End If