ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

获取设备Ip地址

2026/8/27 12:51:37 拓冰建站 浏览量
获取设备Ip地址 获取mac地址且缓存usingSystem;usingSystem.Net.NetworkInformation;usingUnityEngine;publicstaticclassMacAddressDeviceUtil{/// summary/// 获取本机固定的物理 MAC 地址优先获取主板物理以太网卡不受网络切换影响/// /summary/// param namewithSpaces是否在冒号后面加空格/parampublicstaticstringGetStableMacAddress(boolwithSpacesfalse){stringprefKeywithSpaces?StableMacAddress_Spaced:StableMacAddress;// 1. 尝试从本地持久化缓存中读取保证只要这台电脑运行过一次MAC 永久不变if(PlayerPrefs.HasKey(prefKey)){stringcachedMacPlayerPrefs.GetString(prefKey);if(!string.IsNullOrEmpty(cachedMac)cachedMac!00:00:00:00:00:00){returncachedMac;}}stringfoundMac00:00:00:00:00:00;try{NetworkInterface[]interfacesNetworkInterface.GetAllNetworkInterfaces();stringbackupMacnull;foreach(NetworkInterfaceniininterfaces){if(ni.NetworkInterfaceTypeNetworkInterfaceType.Loopback||ni.NetworkInterfaceTypeNetworkInterfaceType.Tunnel){continue;}stringdescni.Description.ToLower();if(desc.Contains(virtual)||desc.Contains(vmware)||desc.Contains(hyper-v)||desc.Contains(bluetooth)||desc.Contains(tap-windows)||desc.Contains(pseudo)){continue;}PhysicalAddresspani.GetPhysicalAddress();byte[]bytespa.GetAddressBytes();if(bytes!nullbytes.Length6){stringmacFormatMacAddress(bytes,withSpaces);if(ni.NetworkInterfaceTypeNetworkInterfaceType.Ethernet){foundMacmac;break;// 找到了物理以太网卡停止搜索}if(string.IsNullOrEmpty(backupMac)){backupMacmac;}}}if(foundMac00:00:00:00:00:00!string.IsNullOrEmpty(backupMac)){foundMacbackupMac;}}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[]hexArraynewstring[bytes.Length];for(inti0;ibytes.Length;i){hexArray[i]bytes[i].ToString(X2);}returnwithSpaces?string.Join(: ,hexArray):string.Join(:,hexArray);}}1获取本地Ip地址/// summary/// 获取本机IPv4地址全平台兼容不依赖Dns.GetHostName/// /summarystringGetLocalIPAddress(){stringlocalIPstring.Empty;try{// 遍历所有网络接口varnetworkInterfacesNetworkInterface.GetAllNetworkInterfaces().Where(nn.NetworkInterfaceType!NetworkInterfaceType.Loopback// 排除回环n.OperationalStatusOperationalStatus.Up);// 只取启用的网卡foreach(varnetworkInterfaceinnetworkInterfaces){varaddressesnetworkInterface.GetIPProperties().UnicastAddresses;foreach(varaddressinaddresses){// 只取IPv4地址if(address.Address.AddressFamilyAddressFamily.InterNetwork){localIPaddress.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地址/// /summarystringGetLocalIPAddress(){if(Application.platformRuntimePlatform.Android){stringlocalIPstring.Empty;varnetworkInterfacesNetworkInterface.GetAllNetworkInterfaces().Where(nn.NetworkInterfaceType!NetworkInterfaceType.Loopbackn.OperationalStatusOperationalStatus.Up);foreach(varnetworkInterfaceinnetworkInterfaces){varaddressesnetworkInterface.GetIPProperties().UnicastAddresses;foreach(varaddressinaddresses){if(address.Address.AddressFamilyAddressFamily.InterNetwork){localIPaddress.Address.ToString();break;}}if(!string.IsNullOrEmpty(localIP))break;}returnlocalIP;}else{returnDns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(oo.AddressFamilyAddressFamily.InterNetwork)?.ToString();}}/// summary/// 获取本机的mac地址/// /summaryprivatestringGetMacAddress(){NetworkInterface[]nicsNetworkInterface.GetAllNetworkInterfaces();foreach(NetworkInterfaceadapterinnics){if(adapter.NetworkInterfaceTypeNetworkInterfaceType.Ethernet||adapter.NetworkInterfaceTypeNetworkInterfaceType.Wireless80211){PhysicalAddressaddressadapter.GetPhysicalAddress();byte[]bytesaddress.GetAddressBytes();stringmacAddress;for(inti0;ibytes.Length;i){macAddressbytes[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{publicListstringIPAddressesnewListstring();publicListstringMacAddressesnewListstring();privatevoidStart(){Main();}publicvoidMain(){DictionaryIPAddress,PhysicalAddressallGetAllDevicesOnLAN();foreach(KeyValuePairIPAddress,PhysicalAddresskvpinall){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 namepIpNetTable/param/// param namepdwSize/param/// param namebOrder/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/// /summaryconstintERROR_INSUFFICIENT_BUFFER122;/// 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/returnsprivatestaticDictionaryIPAddress,PhysicalAddressGetAllDevicesOnLAN(){DictionaryIPAddress,PhysicalAddressallnewDictionaryIPAddress,PhysicalAddress();// Add this PC to the list...all.Add(GetIPAddress(),GetMacAddress());intspaceForNetTable0;// 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.IntPtrrawTableIntPtr.Zero;try{rawTableMarshal.AllocCoTaskMem(spaceForNetTable);// Get the actual datainterrorCodeGetIpNetTable(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 countintrowsCountMarshal.ReadInt32(rawTable);IntPtrcurrentBuffernewIntPtr(rawTable.ToInt64()Marshal.SizeOf(typeof(Int32)));// Convert the raw table to individual entriesMIB_IPNETROW[]rowsnewMIB_IPNETROW[rowsCount];for(intindex0;indexrowsCount;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)PhysicalAddressvirtualMACnewPhysicalAddress(newbyte[]{0,0,0,0,0,0});PhysicalAddressbroadcastMACnewPhysicalAddress(newbyte[]{255,255,255,255,255,255});foreach(MIB_IPNETROWrowinrows){IPAddressipnewIPAddress(BitConverter.GetBytes(row.dwAddr));byte[]rawMACnewbyte[]{row.mac0,row.mac1,row.mac2,row.mac3,row.mac4,row.mac5};PhysicalAddresspanewPhysicalAddress(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/returnsprivatestaticIPAddressGetIPAddress(){StringstrHostNameDns.GetHostName();IPHostEntryipEntryDns.GetHostEntry(strHostName);IPAddress[]addripEntry.AddressList;foreach(IPAddressipinaddr){if(!ip.IsIPv6LinkLocal){return(ip);}}returnaddr.Length0?addr[0]:null;}/// summary/// Gets the MAC address of the current PC./// /summary/// returns/returnsprivatestaticPhysicalAddressGetMacAddress(){foreach(NetworkInterfacenicinNetworkInterface.GetAllNetworkInterfaces()){// Only consider Ethernet network interfacesif(nic.NetworkInterfaceTypeNetworkInterfaceType.Ethernetnic.OperationalStatusOperationalStatus.Up){returnnic.GetPhysicalAddress();}}returnnull;}/// summary/// Returns true if the specified IP address is a multicast address/// /summary/// param nameip/param/// returns/returnsprivatestaticboolIsMulticast(IPAddressip){boolresulttrue;if(!ip.IsIPv6Multicast){bytehighIPip.GetAddressBytes()[0];if(highIP224||highIP239){resultfalse;}}returnresult;}}