会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
X-Zone
用技术去改变生活,
热爱技术,享受生活……
首页
新随笔
新文章
联系
管理
订阅
C# 获取 MAC地址!
最近项目中需要一个方法,来获取本机的MAC地址。
本人最后找到两种方法来实现此功能:
方法一:直接获取
using
System;
using
System.Management;
namespace
PublicBill.GetMAC
{
class
GetMAC
{
[STAThread]
static
void
Main(
string
[] args)
{
string
mac
=
""
;
ManagementClass mc
=
new
ManagementClass(
"
Win32_NetworkAdapterConfiguration
"
);
ManagementObjectCollection moc
=
mc.GetInstances();
foreach
(ManagementObject mo
in
moc)
{
if
(mo[
"
IPEnabled
"
].ToString()
==
"
True
"
)
{
mac
=
mo[
"
MacAddress
"
].ToString();
}
}
Console.WriteLine(
"
MAC Address:
"
+
mac.ToString());
}
}
}
方法二:ARP协议的解析原理获取MAC地址
using
System;
using
System.Runtime.InteropServices;
using
System.Net;
namespace
GetMacAddress
{
class
MAC
{
[DllImport(
"
Iphlpapi.dll
"
)]
private
static
extern
int
SendARP(Int32 dest,Int32 host,
ref
ulong
mac,
ref
IntPtr length);
[DllImport(
"
Ws2_32.dll
"
)]
private
static
extern
Int32 inet_addr(
string
ip);
[STAThread]
static
void
Main(
string
[] args)
{
IPHostEntry hostInfo
=
Dns.GetHostByName(Dns.GetHostName());
IPAddress[] addrs
=
hostInfo.AddressList;
IPAddress ipAddress
=
addrs[
0
];
Int32 ldest
=
inet_addr(ipAddress.ToString());
try
{
Int32 length
=
6
;
ulong
mac
=
0
;
IntPtr len
=
new
IntPtr(length);
int
ii
=
SendARP(ldest,
0
,
ref
mac,
ref
len);
string
l
=
""
;
string
h
=
""
;
int
n
=
1
;
long
m
=
0
;
long
lm
=
(
long
)mac;
while
(lm
>
0
)
{
m
=
lm
%
16
;
lm
=
lm
/
16
;
if
(m
>
9
)
{
if
(m
==
10
)l
=
"
A
"
+
l;
if
(m
==
11
)l
=
"
B
"
+
l;
if
(m
==
12
)l
=
"
C
"
+
l;
if
(m
==
13
)l
=
"
D
"
+
l;
if
(m
==
14
)l
=
"
E
"
+
l;
if
(m
==
15
)l
=
"
F
"
+
l;
}
else
{
l
=
m.ToString()
+
1
;
}
if
((n
%
2
)
==
0
)
{
h
=
h
+
1
;
l
=
""
;
}
++
n;
}
Console.WriteLine(
"
IP Address:
"
+
ipAddress.ToString());
Console.WriteLine(
"
MAC Address:
"
+
h);
}
catch
(Exception error)
{
Console.WriteLine(error);
}
}
}
}
posted on
2005-10-09 11:21
10cn.net
阅读(
422
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告