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);
}
}
}
}
查看全文
相关阅读:
A magic method allowing a third variable used in comparison function of std::sort
Create a wireframe box in rviz but not using any other extra tools (unfinished)
Three methods to iterate every point in pointcloud of PCL(三种遍历点云的方式)
Environment Perception: 3D Truss Environment Mapping and Parametric Expression Extraction
shell脚本练习02--求字符串的长度
shell脚本练习01
shell脚本,循环的记录
linux 备份最近一天的文件
mybatis和java一些知识记录
第8章
原文地址:https://www.cnblogs.com/publicbill/p/250766.html
最新文章
Jingle 相关问题
如何面试
安装phonegap3.2
wordpress 安装 "Table Prefix" must not be empty.
Redis这些知识你知道吗?
如何有效的阅读JDK源码
Java多线程问题40个
浅谈服务架构“五脏六腑”之Spring Cloud
Java中性能优化的45个细节
Spring中应用的那些设计模式
热门文章
Java工程师常用Linux命令
数据结构中的堆栈和内存中的堆栈不是一回事
JVM中内存分配策略及堆和栈的比较
MySQL常用存储引擎:MyISAM与InnoDB之华山论剑
ROS crashed after rebooting the computer
Jewels and Stones
Ubuntu 16.04 install CloudCompare
Keep reinstalling rtabmap and rtabmap_ros
Launch rtabmap_ros with kinect2
Launch rtabmap_ros with kinect 1
Copyright © 2011-2022 走看看