获取mac地址且缓存
usingSystem;usingSystem.Net.NetworkInformation;usingUnityEngine;publicstaticclassMacAddressDeviceUtil{/// <summary>/// 获取本机固定的物理 MAC 地址(优先获取主板物理以太网卡,不受网络切换影响)/// </summary>/// <param name="withSpaces">是否在冒号后面加空格</param>publicstaticstringGetStableMacAddress(boolwithSpaces=false){stringprefKey=withSpaces?"StableMacAddress_Spaced":"StableMacAddress";// 1. 尝试从本地持久化缓存中读取,保证只要这台电脑运行过一次,MAC 永久不变if(PlayerPrefs.HasKey(prefKey)){stringcachedMac=PlayerPrefs.GetString(prefKey);if(!string.IsNullOrEmpty(cachedMac)&&cachedMac!="00:00:00:00:00:00"){returncachedMac;}}stringfoundMac="00:00:00:00:00:00";try{NetworkInterface[]interfaces=NetworkInterface.GetAllNetworkInterfaces();stringbackupMac=null;foreach(NetworkInterfaceniininterfaces){if(ni.NetworkInterfaceType==NetworkInterfaceType.Loopback||ni.NetworkInterfaceType==NetworkInterfaceType.Tunnel){continue;}stringdesc=ni.Description.ToLower();if(desc.Contains("virtual")||desc.Contains("vmware")||desc.Contains("hyper-v")||desc.Contains("bluetooth")||desc.Contains("tap-windows")||desc.Contains("pseudo")){continue;}PhysicalAddresspa=ni.GetPhysicalAddress();byte[]bytes=pa.GetAddressBytes();if(bytes!=null&&bytes.Length==6){stringmac=FormatMacAddress(bytes,withSpaces);if(ni.NetworkInterfaceType==NetworkInterfaceType.Ethernet){foundMac=mac;break;// 找到了物理以太网卡,停止搜索}if(string.IsNullOrEmpty(backupMac)){backupMac=mac;}}}if(foundMac=="00:00:00:00:00:00"&&!string.IsNullOrEmpty(backupMac)){foundMac=backupMac;}}catch(Exceptione){Debug.LogError($"获取 MAC 地址失败:{e.Message}");}// 2. 将有效的结果持久化保存,彻底锁定此电脑的 MACif(foundMac!="00:00:00:00:00:00"){PlayerPrefs.SetString(prefKey,foundMac);PlayerPrefs.Save();}returnfoundMac;}privatestaticstringFormatMacAddress(byte[]bytes,boolwithSpaces){string[]hexArray=newstring[bytes.Length];for(inti=0;i<bytes.Length;i++){hexArray[i]=bytes[i].ToString("X2");}returnwithSpaces?string.Join(": ",hexArray):string.Join(":",hexArray);}}1,获取本地Ip地址
/// <summary>/// 获取本机IPv4地址(全平台兼容,不依赖Dns.GetHostName)/// </summary>stringGetLocalIPAddress(){stringlocalIP=string.Empty;try{// 遍历所有网络接口varnetworkInterfaces=NetworkInterface.GetAllNetworkInterfaces().Where(n=>n.NetworkInterfaceType!=NetworkInterfaceType.Loopback&&// 排除回环n.OperationalStatus==OperationalStatus.Up);// 只取启用的网卡foreach(varnetworkInterfaceinnetworkInterfaces){varaddresses=networkInterface.GetIPProperties().UnicastAddresses;foreach(varaddressinaddresses){// 只取IPv4地址if(address.Address.AddressFamily==AddressFamily.InterNetwork){localIP=address.Address.ToString();break;}}if(!string.IsNullOrEmpty(localIP))break;}}catch(Exceptione){Debug.LogError("获取本地IP失败:"+e.Message);}// 兜底返回本地回环地址,避免空值returnstring.IsNullOrEmpty(localIP)?"127.0.0.1":localIP;}/// <summary>/// 获取本机IP地址/// </summary>stringGetLocalIPAddress(){if(Application.platform==RuntimePlatform.Android){stringlocalIP=string.Empty;varnetworkInterfaces=NetworkInterface.GetAllNetworkInterfaces().Where(n=>n.NetworkInterfaceType!=NetworkInterfaceType.Loopback&&n.OperationalStatus==OperationalStatus.Up);foreach(varnetworkInterfaceinnetworkInterfaces){varaddresses=networkInterface.GetIPProperties().UnicastAddresses;foreach(varaddressinaddresses){if(address.Address.AddressFamily==AddressFamily.InterNetwork){localIP=address.Address.ToString();break;}}if(!string.IsNullOrEmpty(localIP))break;}returnlocalIP;}else{returnDns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(o=>o.AddressFamily==AddressFamily.InterNetwork)?.ToString();}}/// <summary>/// 获取本机的mac地址/// </summary>privatestringGetMacAddress(){NetworkInterface[]nics=NetworkInterface.GetAllNetworkInterfaces();foreach(NetworkInterfaceadapterinnics){if(adapter.NetworkInterfaceType==NetworkInterfaceType.Ethernet||adapter.NetworkInterfaceType==NetworkInterfaceType.Wireless80211){PhysicalAddressaddress=adapter.GetPhysicalAddress();byte[]bytes=address.GetAddressBytes();stringmacAddress="";for(inti=0;i<bytes.Length;i++){macAddress+=bytes[i].ToString("X2");if(i!=bytes.Length-1)macAddress+=":";}//Debug.Log("MAC Address: " + macAddress);returnmacAddress;}}returnnull;}2,获取局域网内所有ip地址和mac地址
usingSystem;usingSystem.Runtime.InteropServices;usingSystem.Collections.Generic;usingSystem.Net;usingSystem.Net.NetworkInformation;usingUnityEngine;publicclassT:MonoBehaviour{publicList<string>IPAddresses=newList<string>();publicList<string>MacAddresses=newList<string>();privatevoidStart(){Main();}publicvoidMain(){Dictionary<IPAddress,PhysicalAddress>all=GetAllDevicesOnLAN();foreach(KeyValuePair<IPAddress,PhysicalAddress>kvpinall){IPAddresses.Add(kvp.Key.ToString());MacAddresses.Add(kvp.Value.ToString());}}/// <summary>/// MIB_IPNETROW structure returned by GetIpNetTable/// DO NOT MODIFY THIS STRUCTURE./// </summary>[StructLayout(LayoutKind.Sequential)]structMIB_IPNETROW{[MarshalAs(UnmanagedType.U4)]publicintdwIndex;[MarshalAs(UnmanagedType.U4)]publicintdwPhysAddrLen;[MarshalAs(UnmanagedType.U1)]publicbytemac0;[MarshalAs(UnmanagedType.U1)]publicbytemac1;[MarshalAs(UnmanagedType.U1)]publicbytemac2;[MarshalAs(UnmanagedType.U1)]publicbytemac3;[MarshalAs(UnmanagedType.U1)]publicbytemac4;[MarshalAs(UnmanagedType.U1)]publicbytemac5;[MarshalAs(UnmanagedType.U1)]publicbytemac6;[MarshalAs(UnmanagedType.U1)]publicbytemac7;[MarshalAs(UnmanagedType.U4)]publicintdwAddr;[MarshalAs(UnmanagedType.U4)]publicintdwType;}/// <summary>/// GetIpNetTable external method/// </summary>/// <param name="pIpNetTable"></param>/// <param name="pdwSize"></param>/// <param name="bOrder"></param>/// <returns></returns>[DllImport("IpHlpApi.dll")][return:MarshalAs(UnmanagedType.U4)]staticexternintGetIpNetTable(IntPtrpIpNetTable,[MarshalAs(UnmanagedType.U4)]refintpdwSize,boolbOrder);/// <summary>/// Error codes GetIpNetTable returns that we recognise/// </summary>constintERROR_INSUFFICIENT_BUFFER=122;/// <summary>/// Get the IP and MAC addresses of all known devices on the LAN/// </summary>/// <remarks>/// 1) This table is not updated often - it can take some human-scale time/// to notice that a device has dropped off the network, or a new device/// has connected./// 2) This discards non-local devices if they are found - these are multicast/// and can be discarded by IP address range./// </remarks>/// <returns></returns>privatestaticDictionary<IPAddress,PhysicalAddress>GetAllDevicesOnLAN(){Dictionary<IPAddress,PhysicalAddress>all=newDictionary<IPAddress,PhysicalAddress>();// Add this PC to the list...all.Add(GetIPAddress(),GetMacAddress());intspaceForNetTable=0;// Get the space needed// We do that by requesting the table, but not giving any space at all.// The return value will tell us how much we actually need.GetIpNetTable(IntPtr.Zero,refspaceForNetTable,false);// Allocate the space// We use a try-finally block to ensure release.IntPtrrawTable=IntPtr.Zero;try{rawTable=Marshal.AllocCoTaskMem(spaceForNetTable);// Get the actual datainterrorCode=GetIpNetTable(rawTable,refspaceForNetTable,false);if(errorCode!=0){// Failed for some reason - can do no more here.thrownewException(string.Format("Unable to retrieve network table. Error code {0}",errorCode));}// Get the rows countintrowsCount=Marshal.ReadInt32(rawTable);IntPtrcurrentBuffer=newIntPtr(rawTable.ToInt64()+Marshal.SizeOf(typeof(Int32)));// Convert the raw table to individual entriesMIB_IPNETROW[]rows=newMIB_IPNETROW[rowsCount];for(intindex=0;index<rowsCount;index++){rows[index]=(MIB_IPNETROW)Marshal.PtrToStructure(newIntPtr(currentBuffer.ToInt64()+(index*Marshal.SizeOf(typeof(MIB_IPNETROW)))),typeof(MIB_IPNETROW));}// Define the dummy entries list (we can discard these)PhysicalAddressvirtualMAC=newPhysicalAddress(newbyte[]{0,0,0,0,0,0});PhysicalAddressbroadcastMAC=newPhysicalAddress(newbyte[]{255,255,255,255,255,255});foreach(MIB_IPNETROWrowinrows){IPAddressip=newIPAddress(BitConverter.GetBytes(row.dwAddr));byte[]rawMAC=newbyte[]{row.mac0,row.mac1,row.mac2,row.mac3,row.mac4,row.mac5};PhysicalAddresspa=newPhysicalAddress(rawMAC);if(!pa.Equals(virtualMAC)&&!pa.Equals(broadcastMAC)&&!IsMulticast(ip)){//Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString());if(!all.ContainsKey(ip)){all.Add(ip,pa);}}}}finally{// Release the memory.Marshal.FreeCoTaskMem(rawTable);}returnall;}/// <summary>/// Gets the IP address of the current PC/// </summary>/// <returns></returns>privatestaticIPAddressGetIPAddress(){StringstrHostName=Dns.GetHostName();IPHostEntryipEntry=Dns.GetHostEntry(strHostName);IPAddress[]addr=ipEntry.AddressList;foreach(IPAddressipinaddr){if(!ip.IsIPv6LinkLocal){return(ip);}}returnaddr.Length>0?addr[0]:null;}/// <summary>/// Gets the MAC address of the current PC./// </summary>/// <returns></returns>privatestaticPhysicalAddressGetMacAddress(){foreach(NetworkInterfacenicinNetworkInterface.GetAllNetworkInterfaces()){// Only consider Ethernet network interfacesif(nic.NetworkInterfaceType==NetworkInterfaceType.Ethernet&&nic.OperationalStatus==OperationalStatus.Up){returnnic.GetPhysicalAddress();}}returnnull;}/// <summary>/// Returns true if the specified IP address is a multicast address/// </summary>/// <param name="ip"></param>/// <returns></returns>privatestaticboolIsMulticast(IPAddressip){boolresult=true;if(!ip.IsIPv6Multicast){bytehighIP=ip.GetAddressBytes()[0];if(highIP<224||highIP>239){result=false;}}returnresult;}}