C#_获取本机IP地址与MAC地址

前段时间做一个小工具,需要获取本机的IP地址与Mac地址,记录下相关方法

话不多说,直接上代码

获取物理地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public static string GetMacAddress()
{
string macAdress = "";
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in nics)
{
PhysicalAddress address = adapter.GetPhysicalAddress();
if (address.ToString() != "")
{
byte[] macBytes = address.GetAddressBytes();
for (int i = 0; i < macBytes.Length; ++i)
{
if (i == 0)
{
macAdress += string.Format("{0:X2}", macBytes[i]);
}
else
{
macAdress += string.Format("-{0:X2}", macBytes[i]);
}
}
LogModule.Log("自动获取物理地址为!" + macAdress);
return macAdress;
}
}
return string.Empty;
}

获取ip地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/// <summary>
/// 获取当前使用的IP
/// </summary>
/// <returns></returns>
public static string GetLocalIP()
{
string result = RunApp("route", "print", true);
Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
if (m.Success)
{
return m.Groups[2].Value;
}
else
{
try
{
System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
c.Connect("www.baidu.com", 80);
string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
c.Close();
return ip;
}
catch (Exception e)
{
return null;
}
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!