获得MAC地址的四个方法

转载 2006年06月01日 19:47:00

1.使用WMI查询表Win32_NetworkAdapterConfiguration即可获得。

2.使用ARP协议。请看这里

3.使用Windows命令nbtstat,也就是通过NetBIOS请看这里

4.查询SNMP(就是一种用于监视网络设备的协议)的MIB(管理信息数据库)。但这不是一件简单的事情,需要自己创建SNMP包,发送到交换机,然后对返回的响应进行解析。

下面是代碼:

using System;
using System.Diagnostics;
using System.Management;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace MACAddress
{
    
/// <summary>
    
/// MainClass 的摘要描述。
    
/// </summary>

    internal class MainClass
    
{
        
/// <summary>
        
/// 應用程式的主進入點。
        
/// </summary>

        [STAThread]
        
private static void Main(string[] args)
        
{
            GetMACByWMI();
            IPAddress[] ips 
= GetLocalIP();
            
foreach (IPAddress ip in ips)
            
{
                Console.WriteLine(GetMacByARP(ip.ToString()));
                
string mac = GetRemoteMacByNetBIOS(ip.ToString());
                
if ( mac.Length != 0 )
                    Console.WriteLine(mac);
                
else
                    Console.WriteLine(
"Fail to get MACAddress by NetBIOS");
                GetMACBySNMP(ip.ToString(),
"yourGroupName@yourVlanNumber");
            }

            Console.ReadLine();
        }


        
By WMI

        
#region By ARP

        [DllImport(
"Iphlpapi.dll")]
        
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);

        [DllImport(
"Ws2_32.dll")]
        
private static extern Int32 inet_addr(string ip);

        
public static string GetMacByARP(string clientIP)
        
{
            
string ip = clientIP;
            Int32 ldest 
= inet_addr(ip);
            Int64 macinfo 
= new Int64();
            Int32 len 
= 6;
            
try
            
{
                SendARP(ldest, 
0ref macinfo, ref len);
            }

            
catch
            
{
                
return "";
            }

            
string originalMACAddress = Convert.ToString(macinfo, 16);
            
if (originalMACAddress.Length < 12)
            
{
                originalMACAddress 
= originalMACAddress.PadLeft(12'0');
            }

            
string macAddress;
            
if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
            
{
                
string mac1, mac2, mac3, mac4, mac5, mac6;
                mac1 
= originalMACAddress.Substring(102);
                mac2 
= originalMACAddress.Substring(82);
                mac3 
= originalMACAddress.Substring(62);
                mac4 
= originalMACAddress.Substring(42);
                mac5 
= originalMACAddress.Substring(22);
                mac6 
= originalMACAddress.Substring(02);
                macAddress 
= mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
            }

            
else
            
{
                macAddress 
= "";
            }

            
return macAddress.ToUpper();
        }


        
public static IPAddress[] GetLocalIP()
        
{
            
string hostName = Dns.GetHostName();
            IPHostEntry ipEntry 
= Dns.GetHostByName(hostName);
            
return ipEntry.AddressList;
        }


        
#endregion


        
#region By NetBIOS
        
public static string GetRemoteMacByNetBIOS(string clientIP)
        
{
            
string ip = clientIP;
            
string dirResults = "";
            ProcessStartInfo psi 
= new ProcessStartInfo();
            Process proc 
= new Process();
            psi.FileName 
= "nbtstat.exe";
            
//psi.RedirectStandardInput = false; 
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError 
= true;
            psi.Arguments 
= "-A " + ip;
            psi.UseShellExecute 
= false;
            proc 
= Process.Start(psi);
            dirResults 
= proc.StandardOutput.ReadToEnd();
            
string error = proc.StandardError.ReadToEnd();
            proc.WaitForExit();
            dirResults 
= dirResults.Replace("/r""").Replace("/n""").Replace("/t""");
            Regex reg 
= new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Match mc 
= reg.Match(dirResults + "__MAC");
            
if (mc.Success)
            
{
                
return mc.Groups["key"].Value.ToUpper();
            }

            
else
            
{
                
return "";
            }

        }

        
#endregion


        
#region By SNMP
        
public static void GetMACBySNMP(string ip,string vlan)
        
{
            
int commLength,mibLength,dataStart,dataLength;
            
string nextMib,value;
            SNMP conn 
= new SNMP();
            
string mib = "1.3.6.1.2.1.17.4.3.1.1";
            
int orgMibLength = mib.Length;
            
byte[] response = new byte[1024];

            nextMib 
= mib;

            
while ( true)
            
{
                response 
= conn.Get("getnext",ip,vlan,nextMib);
                commLength 
= Convert.ToInt16(response[6]);
                mibLength 
= Convert.ToInt16(response[23+commLength]);
                dataLength 
= Convert.ToInt16(response[25+commLength+mibLength]);
                dataStart 
= 26 + commLength + mibLength;
                value 
= BitConverter.ToString(response,dataStart,dataLength);
                nextMib 
= conn.GetNextMIB(response);

                
if ( !(nextMib.Substring(0,orgMibLength) == mib))
                
{
                    
break;
                }

                Console.WriteLine(
"{0}={1}",nextMib,value);

            }

        }

        
#endregion

    }

}


SNMP Class


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace MACAddress
{
    
/**//// <summary>
    
/// SNMP 的摘要描述。
    
/// </summary>

    public class SNMP
    
{
        
public SNMP()
        
{
        }


        
public byte[] Get(string request, string host, string community, string mibString)
        
{
            
byte[] packet = new byte[1024];
            
byte[] mib = new byte[1024];
            
int snmpLen;
            
int comLen = community.Length;
            
string[] mibVals = mibString.Split('.');
            
int mibLen = mibVals.Length;
            
int cnt = 0;
            
int temp;
            
int orgmibLen = mibLen;
            
int pos = 0;
            
for (int i = 0; i < orgmibLen; i++)
            
{
                temp 
= Convert.ToInt16(mibVals[i]);
                
if (temp > 127)
                
{
                    mib[cnt] 
= Convert.ToByte(128 + (temp / 128));
                    mib[cnt 
+ 1= Convert.ToByte(temp - ((temp / 128* 128));
                    cnt 
+= 2;
                    mibLen
++;
                }

                
else
                
{
                    mib[cnt] 
= Convert.ToByte(temp);
                    cnt
++;
                }

            }


            snmpLen 
= 29 + comLen + mibLen - 1;
            packet[pos
++= 0x30;
            packet[pos
++= Convert.ToByte(snmpLen - 2);

            packet[pos
++= 0x02;
            packet[pos
++= 0x01;
            packet[pos
++= 0x00;

            packet[pos
++= 0x04;
            packet[pos
++= Convert.ToByte(comLen);
            
byte[] data = Encoding.ASCII.GetBytes(community);
            
for (int i = 0; i < data.Length; i++)
            
{
                packet[pos
++= data[i];
            }


            
if (request == "get")
            
{
                packet[pos
++= 0xA0;
            }

            
else
            
{
                packet[pos
++= 0xA1;
            }

            packet[pos
++= Convert.ToByte(20 + mibLen - 1);

            packet[pos
++= 0x02;
            packet[pos
++= 0x04;
            packet[pos
++= 0x00;
            packet[pos
++= 0x00;
            packet[pos
++= 0x00;
            packet[pos
++= 0x01;

            packet[pos
++= 0x02;
            packet[pos
++= 0x01;
            packet[pos
++= 0x00;

            packet[pos
++= 0x02;
            packet[pos
++= 0x01;
            packet[pos
++= 0x00;

            packet[pos
++= 0x30;

            packet[pos
++= Convert.ToByte(6 + mibLen - 1);
            packet[pos
++= 0x30;
            packet[pos
++= Convert.ToByte(6 + mibLen - 1 - 2);
            packet[pos
++= 0x06;
            packet[pos
++= Convert.ToByte(mibLen - 1);

            packet[pos
++= 0x2b;
            
for (int i = 2; i < mibLen; i++)
            
{
                packet[pos
++= Convert.ToByte(mib[i]);
            }

            packet[pos
++= 0x05;
            packet[pos
++= 0x00;

            Socket sock 
= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 
5000);
            IPHostEntry ihe 
= Dns.Resolve(host);
            IPEndPoint iep 
= new IPEndPoint(ihe.AddressList[0], 161);
            EndPoint ep 
= (EndPoint) iep;
            sock.SendTo(packet, snmpLen, SocketFlags.None, iep);

            
try
            
{
                
int recv = sock.ReceiveFrom(packet, ref ep);
            }

            
catch (SocketException)
            
{
                packet[
0= 0xff;
            }

            
return packet;
        }


        
public string GetNextMIB(byte[] mibIn)
        
{
            
string output = "1.3";
            
int commLength = mibIn[6];
            
int mibStart = 6 + commLength + 17;
            
int mibLength = mibIn[mibStart] - 1;
            mibStart 
+= 2;
            
int mibValue;

            
for (int i = mibStart; i < mibStart + mibLength; i++)
            
{
                mibValue 
= Convert.ToInt16(mibIn[i]);
                
if (mibValue > 128)
                
{
                    mibValue 
= (mibValue / 128* 128 + Convert.ToInt16(mibIn[i + 1]);
                    i
++;
                }

                output 
+= "." + mibValue;
            }

            
return output;
        }

    }

}


 如果还有其它方法,请告诉我。

相关文章推荐

修改MAC地址方法

  • 2013-05-11 01:06
  • 48KB
  • 下载

VMware ESXI虚拟机及虚拟系统修改MAC地址的方法

参考: VMware ESXI(5.1下测试)在新建虚拟机(windows或linux)时,网络适配器MAC地址默认为“自动”,获得的MAC地址根据ethernet0.addressType值的...

C#读网卡MAC地址-WMI方法

昨天听测试组的工程师们在讨论怎么用批处理(DOS)把MAC都出来,保存到文本文件中。观察了一会,看的蛋疼。然后网上搜了一通代码,互联网的搬码工的活就算完了。测试也OK。     今天又回头看了一下,...

MAC地址的绑定方法

  • 2014-04-10 10:00
  • 302KB
  • 下载

获取mac地址的几种方法

  • 2016-12-13 09:30
  • 31KB
  • 下载

JS获取客户端IP地址、MAC和主机名的7个方法汇总

这篇文章主要介绍了JS获取客户端IP地址、MAC和主机名的7个方法汇总,JS本身是不支持获取IP地址等信息的,本文通过其它方法实现,需要的朋友可以参考下 今天在搞JS(javascript)获取客户端...

C获取MAC地址的4种方法

  • 2014-02-18 11:11
  • 34KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)