C#网络工具类NetTools,获取IP/MAC地址|C/S开发框架
C#网络工具类NetTools,获取IP/MAC地址
NetTools.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
namespace CSFrameworkV5.Common
{
/// <summary>
/// C#网络工具类,获取IP/MAC地址
/// </summary>
public class NetTools
{
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int32 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
/// <summary>
/// 获取本机IP
/// </summary>
/// <returns></returns>
public static string GetLocalIP()
{
IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress IP in ipe.AddressList)
{
if (IP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return IP.ToStringEx();
}
return "";
}
/// <summary>
/// 获取第一个MAC地址
/// </summary>
/// <returns></returns>
public static string GetLocalMac()
{
List<string> macs = GetMacByNetworkInterface();
if (macs.Count > 0)
return macs[0];
else
return "";
}
///<summary>
/// 通过NetworkInterface读取网卡Mac
///</summary>
///<returns></returns>
public static List<string> GetMacByNetworkInterface()
{
List<string> macs = new List<string>();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
macs.Add(ni.GetPhysicalAddress().ToStringEx());
}
return macs;
}
/// <summary>
/// 根据本地IP地址获取MAC地址(Windows API函数方式)
/// </summary>
/// <param name="IP"></param>
/// <returns></returns>
public static string GetMACFromIP(string IP)
{
string strRet = "Unknown";
string strIPPattern = @"^\d+\.\d+\.\d+\.\d+$";
Regex objRex = new Regex(strIPPattern);
if (objRex.IsMatch(IP) == true)
{
Int32 intDest = inet_addr(IP);
Int32[] arrMAC = new Int32[2];
Int32 intLen = 6;
int intResult = SendARP(intDest, 0, ref arrMAC[0], ref intLen);
if (intResult == 0)
{
Byte[] arrbyte = new Byte[8];
arrbyte[5] = (Byte)(arrMAC[1] >> 8);
arrbyte[4] = (Byte)arrMAC[1];
arrbyte[3] = (Byte)(arrMAC[0] >> 24);
arrbyte[2] = (Byte)(arrMAC[0] >> 16);
arrbyte[1] = (Byte)(arrMAC[0] >> 8);
arrbyte[0] = (Byte)arrMAC[0];
StringBuilder strbMAC = new StringBuilder();
for (int intIndex = 0; intIndex < 6; intIndex++)
{
if (intIndex > 0) strbMAC.Append("-");
strbMAC.Append(arrbyte[intIndex].ToString("X2"));
}
strRet = strbMAC.ToString();
}
}
return strRet;
}
}
}
测试
//获取第一个MAC地址:00FF84460462
var macd0 = NetTools.GetLocalMac();
//根据本地IP地址获取MAC地址:00-E0-4C-44-17-F4
var macd1 = NetTools.GetMACFromIP("192.168.0.172");
//获取本机IP
var ip = NetTools.GetLocalIP();
//根据本地IP地址获取MAC地址:00-E0-4C-44-17-F4
var macd2 = NetTools.GetMACFromIP(ip);
扫一扫加作者微信