C# WinCE开发中获取MAC与IP地址
1 2 public class SysInfo 3 { 4 private static string[] strEncrypt = new string[] { 5 "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "K", "L", "M", "N", 6 "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", 7 "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP" }; 8 private static Int32 METHOD_BUFFERED = 0; 9 private static Int32 FILE_ANY_ACCESS = 0; 10 private static Int32 FILE_DEVICE_HAL = 0x00000101; 11 private const Int32 ERROR_NOT_SUPPORTED = 0x32; 12 private const Int32 ERROR_INSUFFICIENT_BUFFER = 0x7A; 13 private static Int32 IOCTL_HAL_GET_DEVICEID = ((FILE_DEVICE_HAL) << 16) | ((FILE_ANY_ACCESS) << 14) | ((21) << 2) | (METHOD_BUFFERED); 14 [DllImport("coredll.dll", SetLastError = true)] 15 private static extern bool KernelIoControl(Int32 dwIoControlCode, IntPtr lpInBuf, Int32 nInBufSize, byte[] lpOutBuf, Int32 nOutBufSize, ref Int32 lpBytesReturned); 16 [DllImport("Iphlpapi.dll", EntryPoint = "SendARP")] 17 public static extern uint SendARP(uint DestIP, uint SrcIP, byte[] pMacAddr, ref uint PhyAddrLen); 18 19 20 21 22 /// <summary> 23 /// 获取MAC地址 24 /// </summary> 25 /// <returns></returns> 26 public string GetMac() 27 { 28 uint ip = 0; 29 string mac = string.Empty; 30 //取本机IP列表 31 IPAddress[] ips = Dns.GetHostEntry(Dns.GetHostName()).AddressList; 32 //取本机IP 33 byte[] ipp = ips[1].GetAddressBytes(); 34 ip = (uint)((ipp[0]) | (ipp[1] << 8) | (ipp[2] << 16) | (ipp[3] << 24)); 35 //取MAC 36 byte[] MacAddr = new byte[6]; 37 uint PhyAddrLen = 6; 38 uint hr = SendARP(ip, 0, MacAddr, ref PhyAddrLen); 39 if (MacAddr[0] != 0 || MacAddr[1] != 0 || MacAddr[2] != 0 || MacAddr[3] != 0 || MacAddr[4] != 0 || MacAddr[5] != 0) 40 { 41 mac = MacAddr[0].ToString("X2")+ ":" + MacAddr[1].ToString("X2") + ":" + 42 MacAddr[2].ToString("X2")+ ":" + MacAddr[3].ToString("X2") + ":" + 43 MacAddr[4].ToString("X2") + ":" + MacAddr[5].ToString("X2"); 44 } 45 return mac; 46 } 47 48 49 50 /// <summary> 51 ///获取本机IP 52 /// </summary> 53 /// <returns></returns> 54 public string GetIpAddress() 55 { 56 string strHostName = Dns.GetHostName(); //得到本机的主机名 57 IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP 58 string strAddr = ipEntry.AddressList[1].ToString(); 59 return strAddr; www.2cto.com 60 } 61 }