C#如何获取网卡MAC地址?

CuckooZXP 2004-04-29 05:50:18
如题。又如何获取硬盘序列号?
望高手指点一二。
...全文
1963 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
cuike519 2004-04-29
  • 打赏
  • 举报
回复
以下有几个关于如何得到mac地址的连接,你可以参考一下:
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=391&lngWId=10
http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5437/
http://www.codeguru.com/Cpp/I-N/network/networkinformation/comments.php/c5451/
zhhahuatian 2004-04-29
  • 打赏
  • 举报
回复
study
huangsuipeng 2004-04-29
  • 打赏
  • 举报
回复
用WMI就够了噢
tonghua990613 2004-04-29
  • 打赏
  • 举报
回复
学习
smartcreater 2004-04-29
  • 打赏
  • 举报
回复
//不需要使用paltform invoke 的方法:
//get the MAC through executing the nbtstat.exe

using System.Diagnostics;
using System.Text.RegularExpressions;

///...............
public string GetMac(string IP)
{
string dirResults="";
ProcessStartInfo psi = new ProcessStartInfo();
Process proc = 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("\r","").Replace("\n","").Replace("\t","");
Regex reg=new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?<key>((.)*?))__MAC",RegexOptions.IgnoreCase|RegexOptions.Compiled);
Match mc=reg.Match(dirResults+"__MAC");

if(mc.Success)
{return mc.Groups["key"].Value;}
else
{
reg=new Regex("Host not found",RegexOptions.IgnoreCase|RegexOptions.Compiled);
mc=reg.Match(dirResults);
if(mc.Success)
{return "Host not found!";
}
else
{return "";}
}
}
dahuzizyd 2004-04-29
  • 打赏
  • 举报
回复
http://www.uncj.net/news/show.aspx?id=77
bitsbird 2004-04-29
  • 打赏
  • 举报
回复
如果要想获得远程的地址,需要用sendarp这个函数来实现。具体的代码如下:
[DllImport("Iphlpapi.dll")]
private static unsafe extern int SendARP(Int32 dest,Int32 host,ref IntPtr mac,ref IntPtr length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);

Int32 ldest= inet_addr("157.60.68.163");//目的地的ip
Int32 lhost= inet_addr("157.60.68.33");//本地的ip

try
{
Byte[] macinfo=new Byte[6];
Int32 length=6;

IntPtr mac=new IntPtr(macinfo[0]);
IntPtr len=new IntPtr(6);
int ii=SendARP(ldest,lhost, ref mac, ref len);

Console.WriteLine("Mac Add:"+mac);
Console.WriteLine("length:"+len);


}
catch(Exception err)
{
Console.WriteLine(err);
}
lxhvc 2004-04-29
  • 打赏
  • 举报
回复
public enum NCBCONST
{
NCBNAMSZ =16, /* absolute length of a net name */
MAX_LANA =254, /* lana's in range 0 to MAX_LANA inclusive */
NCBENUM =0x37, /* NCB ENUMERATE LANA NUMBERS */
NRC_GOODRET =0x00, /* good return */
NCBRESET =0x32, /* NCB RESET */
NCBASTAT =0x33, /* NCB ADAPTER STATUS */
NUM_NAMEBUF =30, /* Number of NAME's BUFFER */
}

[StructLayout(LayoutKind.Sequential)]
public struct ADAPTER_STATUS
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=6)]
public byte[] adapter_address;
public byte rev_major;
public byte reserved0;
public byte adapter_type;
public byte rev_minor;
public ushort duration;
public ushort frmr_recv;
public ushort frmr_xmit;
public ushort iframe_recv_err;
public ushort xmit_aborts;
public uint xmit_success;
public uint recv_success;
public ushort iframe_xmit_err;
public ushort recv_buff_unavail;
public ushort t1_timeouts;
public ushort ti_timeouts;
public uint reserved1;
public ushort free_ncbs;
public ushort max_cfg_ncbs;
public ushort max_ncbs;
public ushort xmit_buf_unavail;
public ushort max_dgram_size;
public ushort pending_sess;
public ushort max_cfg_sess;
public ushort max_sess;
public ushort max_sess_pkt_size;
public ushort name_count;
}

[StructLayout(LayoutKind.Sequential)]
public struct NAME_BUFFER
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NCBNAMSZ)]
public byte[] name;
public byte name_num;
public byte name_flags;
}

[StructLayout(LayoutKind.Sequential)]
public struct NCB
{
public byte ncb_command;
public byte ncb_retcode;
public byte ncb_lsn;
public byte ncb_num;
public IntPtr ncb_buffer;
public ushort ncb_length;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NCBNAMSZ)]
public byte[] ncb_callname;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NCBNAMSZ)]
public byte[] ncb_name;
public byte ncb_rto;
public byte ncb_sto;
public IntPtr ncb_post;
public byte ncb_lana_num;
public byte ncb_cmd_cplt;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=10)]
public byte[] ncb_reserve;
public IntPtr ncb_event;
}

[StructLayout(LayoutKind.Sequential)]
public struct LANA_ENUM
{
public byte length;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.MAX_LANA)]
public byte[] lana;
}

[StructLayout(LayoutKind.Auto)]
public struct ASTAT
{
public ADAPTER_STATUS adapt;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NUM_NAMEBUF)]
public NAME_BUFFER[] NameBuff;
}
public class Win32API
{
[DllImport("NETAPI32.DLL")]
public static extern char Netbios(ref NCB ncb);
}
[/code]

2、
[code]
public string GetMacAddress()
{
string addr="";
int cb;
ASTAT adapter;
NCB Ncb=new NCB();
char uRetCode;
LANA_ENUM lenum;

Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
cb = Marshal.SizeOf(typeof(LANA_ENUM));
Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
Ncb.ncb_length = (ushort)cb;
uRetCode = Win32API.Netbios(ref Ncb);
lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));
Marshal.FreeHGlobal(Ncb.ncb_buffer);
if(uRetCode != (short)NCBCONST.NRC_GOODRET)
return "";

for(int i=0; i < lenum.length ;i++)
{
Ncb.ncb_command = (byte)NCBCONST.NCBRESET;
Ncb.ncb_lana_num = lenum.lana[i];
uRetCode = Win32API.Netbios(ref Ncb);
if(uRetCode != (short)NCBCONST.NRC_GOODRET)
return "";

Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;
Ncb.ncb_lana_num = lenum.lana[i];
Ncb.ncb_callname[0]=(byte)'*';
cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER))*(int)NCBCONST.NUM_NAMEBUF;
Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
Ncb.ncb_length = (ushort)cb;
uRetCode = Win32API.Netbios(ref Ncb);
adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));
Marshal.FreeHGlobal(Ncb.ncb_buffer);

if (uRetCode == (short)NCBCONST.NRC_GOODRET)
{
if(i>0)
addr += ":";
addr = string.Format("{0,2:X}{1,2:X}{2,2:X}{3,2:X}{4,2:X}{5,2:X}",
adapter.adapt.adapter_address[0],
adapter.adapt.adapter_address[1],
adapter.adapt.adapter_address[2],
adapter.adapt.adapter_address[3],
adapter.adapt.adapter_address[4],
adapter.adapt.adapter_address[5]);
}
}
return addr.Replace(' ', '0');
}
stoway 2004-04-29
  • 打赏
  • 举报
回复
朋友mingal急问我有关获取远程网卡MAC地址的ASP.net实现。我一开始以为是获取本机MAC地址,说了几种方法给他。由于他还需要获取服务器(本机)相关信息,如硬盘序列号、CPU信息等。于是介绍了个WMI方法给他:

using System.Management;

string strMac = string.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();

foreach(ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
strMac += mo["MacAddress"].ToString() + "
";
}
}

后来才知道他要的是局域网浏览用户的网卡的MAC地址,那可犯难了。后来找到了相关实现代码,大致是使用地址转换协议进行广播查询的,主要是SendArp这个API:

DWORD SendARP(
IPAddr DestIP, // 目的IP 地址
IPAddr SrcIP, // 源IP地址,可选参数,把它填成0不会有问题
PULONG pMacAddr, // 返回的物理地址
PULONG PhyAddrLen // 物理地址的长度
);

在C#中实现为:

[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest,Int32 host,ref IntPtr mac,ref IntPtr length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);

private IntPtr getRemoteMAC(string localIP, string remoteIP)
{
Int32 ldest= inet_addr(remoteIP); //目的地的ip
Int32 lhost= inet_addr(localIP); //本地服务器的ip

try
{
Byte[] macinfo=new Byte[6];
IntPtr mac=new IntPtr(macinfo[0]);
IntPtr len=new IntPtr;
int ii=SendARP(ldest,lhost, ref mac, ref len);
return mac;
}
catch(Exception err)
{
}
return IntPtr.Zero;
}

可是当把得到的IntPtr类型的MAC地址转换为十六进制时,出现了令人不解的一幕。比如我的网卡MAC地址为00-50-BA-29-22-1A,可是转换后的十六进制却是29BA5000。显然是要每两位反过来排序,但是为什么却缺少了 22-1A ?按道理说得到的结果应该是1A2229BA5000。另外,Arp只能获得同一个网段的,不能跨网段!郁闷ing……,有什么更好的方法???

lxhvc 2004-04-29
  • 打赏
  • 举报
回复
http://blog.joycode.com/liuhuimiao/posts/9754.aspx
希望对你有用。

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧