c# 后端获取服务器mac地址
1 namespace GetMacCore 2 { 3 using System; 4 using System.IO; 5 using System.Management; 6 using System.Text; 7 8 internal class Program 9 { 10 public static string GetMacAddress() 11 { 12 try 13 { 14 string str = string.Empty; 15 foreach (ManagementObject obj2 in new ManagementClass("Win32_NetworkAdapterConfiguration").GetInstances()) 16 { 17 if ((bool)obj2["IPEnabled"]) 18 { 19 str = obj2["MacAddress"].ToString(); 20 break; 21 } 22 } 23 return str; 24 } 25 catch 26 { 27 return "unknown"; 28 } 29 } 30 31 public static void Main(string[] args) 32 { 33 string s = "{\"mac\":\"" + GetMacAddress() + "\"}"; 34 byte[] bytes = Encoding.UTF8.GetBytes(s); 35 Stream stream1 = Console.OpenStandardOutput(); 36 stream1.WriteByte((byte)(bytes.Length & 0xff)); 37 stream1.WriteByte((byte)((bytes.Length >> 8) & 0xff)); 38 stream1.WriteByte((byte)((bytes.Length >> 0x10) & 0xff)); 39 stream1.WriteByte((byte)((bytes.Length >> 0x18) & 0xff)); 40 stream1.Write(bytes, 0, bytes.Length); 41 stream1.Flush(); 42 Console.ReadLine(); 43 stream1.Close(); 44 } 45 46 private static string OpenStandardStreamIn() 47 { 48 Stream stream = Console.OpenStandardInput(); 49 int num = 0; 50 byte[] buffer = new byte[4]; 51 stream.Read(buffer, 0, 4); 52 num = BitConverter.ToInt32(buffer, 0); 53 string str = ""; 54 for (int i = 0; i < num; i++) 55 { 56 str = str + ((char)stream.ReadByte()).ToString(); 57 } 58 return str; 59 } 60 } 61 }