zoukankan
html css js c++ java
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);
}
}
}
}
查看全文
相关阅读:
BufferedImage学习记录一
response总结一
Externalizable接口
request 总结一
处理jsp显示文字过长问题
验证码设计
ORA01461: 仅能绑定要插入 LONG 列的 LONG 值
MAP平台在单据中填写好部门后,关闭后重新打开,部门就没有了
MAP平台设置节点选取范围
MAP平台java.lang.StackOverflowError
原文地址:https://www.cnblogs.com/publicbill/p/250766.html
最新文章
magento 怎么把评论显示到产品页面
护眼背景颜色设置
magento常用语言包下载,包括简体中文语言包
ShutDown命令详解
apache虚拟目录配置
javascript中的各种输入限制
php报错
删除Cookie
SQL语句快速添加表的记录
攻击个人电脑
热门文章
读取ServletContext
两本书
从搜索的角度看互联网
C语言程序运行并将结果保存到文件中
Servlet中添加属性
创建Cookie
读取Cookie
final关键字用法总结
@Override
Myeclipse环境背景颜色设置
Copyright © 2011-2022 走看看