C# 获取本机mac地址 客户端主机名称(hostName) 当前用户(CurWinUser) 操作系统版本(WinVersion) IE浏览器版本(IEversion) 物理内存(Memo

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 获取本机mac地址 客户端主机名称(hostName) 当前用户(CurWinUser) 操作系统版本(WinVersion) IE浏览器版本(IEversion) 物理内存(Memo相关的知识,希望对你有一定的参考价值。

  关于获取本机信息的代码,园子里面还是非常多的,专门整理了一下此次用到的信息

  首先,获取跳至网管的IP地址

       #region 获取调至网管的IP地址
        string ipAddress = GetLocalIp();          
        #endregion
        ///此方法需要计算机连网,否则获取不到IP地址
       private string GetLocalIp()
        {
            string result = RunApp("route", "print", true);
            Match m = Regex.Match(result, @"0.0.0.0\\s+0.0.0.0\\s+(\\d+.\\d+.\\d+.\\d+)\\s+(\\d+.\\d+.\\d+.\\d+)");
            if (m.Success)
            {
                return m.Groups[2].Value;
            }
            else
            {
                try
                {
                    System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
                    c.Connect("www.baidu.com", 80);
                    string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                    c.Close();
                    return ip;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
 public static string RunApp(string filename, string arguments, bool recordLog)
        {
            try
            {
                if (recordLog)
                {
                    Trace.WriteLine(filename + " " + arguments);
                }
                Process proc = new Process();
                proc.StartInfo.FileName = filename;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.Arguments = arguments;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.UseShellExecute = false;
                proc.Start();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
                {
                    string txt = sr.ReadToEnd();
                    sr.Close();
                    if (recordLog)
                    {
                        Trace.WriteLine(txt);
                    }
                    if (!proc.HasExited)
                    {
                        proc.Kill();
                    }
                    return txt;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                return ex.Message;
            }
        }

 获取本机mac地址 (获取连接网络网卡的mac地址)

  园子这篇文章写的很好,http://www.cnblogs.com/diulela/archive/2012/04/07/2436111.html,我也是参考这个的

       string macAddre = GetMacBySendARP(ipAdd);
       ///<summary>
        /// 通过SendARP获取网卡Mac
        /// 网络被禁用或未接入网络(如没插网线)时此方法失灵
        ///</summary>
        ///<param name="remoteIP"></param>
        ///<returns></returns>
        public static string GetMacBySendARP(string remoteIP)
        {
            StringBuilder macAddress = new StringBuilder();

            try
            {
                Int32 remote = inet_addr(remoteIP);

                Int64 macInfo = new Int64();
                Int32 length = 6;
                SendARP(remote, 0, ref macInfo, ref length);

                string temp = Convert.ToString(macInfo, 16).PadLeft(12, ‘0‘).ToUpper();

                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5)
                    {
                        macAddress.Append(temp.Substring(x - 2, 2));
                    }
                    else
                    {
                        macAddress.Append(temp.Substring(x - 2, 2) + "-");
                    }
                    x -= 2;
                }

                return macAddress.ToString();
            }
            catch
            {
                return macAddress.ToString();
            }
        }
[DllImport("Iphlpapi.dll")]
privatestaticexternint SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
privatestaticextern Int32 inet_addr(string ip);

 客户端主机名称和当前电脑用户

           #region 获取客户端主机名称
            string hostName = Dns.GetHostName();            
            #endregion           

            #region 获取电脑当前用户
            string  curWinUser=System.Environment.UserName.ToString();
            #endregion

 操作系统版本(WinVersion)  IE浏览器版本(IEversion)

           #region 操作系统版本
            string winVersion = GetCurSysVersion();
            #endregion
         //获取当前操作系统版本
        private string GetCurSysVersion()
        {
            string userAgent = Environment.OSVersion.ToString();
            string osVersion = "未知";

            if (userAgent.Contains("NT 10.0"))
            {
                osVersion = "Windows 10";
            }
            else if (userAgent.Contains("NT 6.3"))
            {
                osVersion = "Windows 8.1";
            }
            else if (userAgent.Contains("NT 6.2"))
            {
                osVersion = "Windows 8";
            }
            else if (userAgent.Contains("NT 6.1"))
            {
                osVersion = "Windows 7";
            }
            else if (userAgent.Contains("NT 6.1"))
            {
                osVersion = "Windows 7";
            }
            else if (userAgent.Contains("NT 6.0"))
            {
                osVersion = "Windows Vista/Server 2008";
            }
            else if (userAgent.Contains("NT 5.2"))
            {
                if (userAgent.Contains("64"))
                    osVersion = "Windows XP";
                else
                    osVersion = "Windows Server 2003";
            }
            else if (userAgent.Contains("NT 5.1"))
            {
                osVersion = "Windows XP";
            }
            else if (userAgent.Contains("NT 5"))
            {
                osVersion = "Windows 2000";
            }
            else if (userAgent.Contains("NT 4"))
            {
                osVersion = "Windows NT4";
            }
            else if (userAgent.Contains("Me"))
            {
                osVersion = "Windows Me";
            }
            else if (userAgent.Contains("98"))
            {
                osVersion = "Windows 98";
            }
            else if (userAgent.Contains("95"))
            {
                osVersion = "Windows 95";
            }
            else if (userAgent.Contains("Mac"))
            {
                osVersion = "Mac";
            }
            else if (userAgent.Contains("Unix"))
            {
                osVersion = "UNIX";
            }
            else if (userAgent.Contains("Linux"))
            {
                osVersion = "Linux";
            }
            else if (userAgent.Contains("SunOS"))
            {
                osVersion = "SunOS";
            }
            else
            {
                osVersion = userAgent;
            }
            return osVersion;
        }
           #region IE浏览器版本
            string IEversion = GetCurIEVersion();
            #endregion
        /// <summary>
        /// 获取当前IE版本
        /// </summary>
        /// <returns></returns>
        private string GetCurIEVersion()
        {
            RegistryKey mreg;
            mreg = Registry.LocalMachine;
            mreg = mreg.CreateSubKey("software\\\\Microsoft\\\\Internet Explorer");
            string IEVersion = (String)mreg.GetValue("Version");
            mreg.Close();
            return IEVersion;
        }

 物理内存使用情况

        /// <summary>
        /// 获取当前系统的物理内存
        /// 需using System.Management;
        /// </summary>
        /// <returns></returns>
        public string GetTotalPhysicalMemory()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["TotalPhysicalMemory"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally { }
        }

        /// <summary>
        /// 获取可用内存
        /// </summary>
        public string MemoryAvailable()
        {
            try
            {
                string availablebytes = "";
                ManagementClass mos = new ManagementClass("Win32_OperatingSystem");
                foreach (ManagementObject mo in mos.GetInstances())
                {
                    if (mo["FreePhysicalMemory"] != null)
                    {
                        availablebytes =(1024 * long.Parse(mo["FreePhysicalMemory"].ToString())).ToString();
                    }
                }
                return availablebytes;
            }
            catch
            {
                return "unknow";
            }
            finally { }                           
        }       

 CPU序列号

        string cupId = GetCpuId();
        /// <summary>
        /// 获取Cpu 序列号
        /// </summary>
        /// <returns></returns>
        private string GetCpuId()
        {
            try
            {
                ManagementClass mClass = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mClass.GetInstances();
                string cpuId = "";
                foreach (ManagementObject mo in moc)
                {
                    cpuId = cpuId + mo.Properties["ProcessorId"].Value.ToString() + " ,";
                    mo.Dispose();
                }
                moc.Dispose();
                mClass.Dispose();
                cpuId = cpuId.Substring(0, cpuId.Length - 1);
                return cpuId;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

 硬盘容量(大小和使用情况(只获取本地硬盘,不包含CDROM u盘和移动硬盘))

            #region 硬盘容量以及使用率
            long totalSpace = 0;
            long freeSpace = 0;
            totalSpace = GetHardDiskInfor(out freeSpace);
            #endregion
        /// <summary>
        /// 获取磁盘信息
        /// </summary>
        /// <param name="freeSpace"></param>
        /// <returns></returns>
        private long GetHardDiskInfor(out long freeSpace)
        {                     
            long totalSpace = 0;
            freeSpace = 0;
            #region DriveInfo获取磁盘信息
            DriveInfo[] drives = DriveInfo.GetDrives(); // 获取所有驱动器信息
            foreach (var drive in drives)
            {
                try
                {
                    if (drive.IsReady) //指示驱动器是否已准备好的值 返回bool类型
                    {
                        if (drive.DriveFormat == "NTFS" && drive.DriveType == System.IO.DriveType.Fixed)//系统磁盘DriveFormat有值
                        {
                            totalSpace = totalSpace + drive.TotalSize / GB;
                            freeSpace = freeSpace + drive.TotalFreeSpace / GB;
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
            #endregion
            return totalSpace;
        }

 已经安装的应用程序(包含64位和32位,其中地址是安装路径或者图标路径)

           #region 已经安装的应用程序
            string instalAppInfor = AlreadyInstallAPP();           
            #endregion
         /// <summary>
        /// 获取所有应用软件目录
        /// </summary>
        /// <returns></returns>
        private string AlreadyInstallAPP()
        {
            StringBuilder infor = new StringBuilder();
            string DisplayName = "";
            string Path = "";
            RegistryKey SubKey = null;
            #region 读取系统应用
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
            if (key != null)//如果系统禁止访问则返回null
            {
                int i = 1;
                foreach (String SubKeyName in key.GetSubKeyNames())
                {                    
                    //打开对应的软件名称
                    SubKey = key.OpenSubKey(SubKeyName);
                    if (SubKey != null)
                    {
                        DisplayName = SubKey.GetValue("DisplayName", "Nothing").ToString();                       
                        //如果没有取到,则不存入动态数组
                        if (DisplayName != "Nothing")
                        {
                            infor.Append("<App id=\\"" + i.ToString() + "\\">");
                            infor.Append("<AppName>" + DisplayName + "</AppName>");
                            Path = SubKey.GetValue("InstallLocation", "").ToString();
                            if (string.IsNullOrEmpty(Path))
                            {
                                Path = SubKey.GetValue("DisplayIcon","").ToString();
                            }
                            infor.Append("<Path>" + Path + "</Path>");
                            infor.Append("</App>");
                            i++;
                        }                       
                    }                    
                }
            }
            #endregion

            #region 若是64位,进行32位应用读取, 若原本是32位系统,不进行下面操作
            RegistryKey Key32 = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall");
            if (Key32 != null)//如果系统禁止访问则返回null
            {
                int i = 1;
                infor.Append("<Win32App>");
                foreach (String SubKeyName in Key32.GetSubKeyNames())
                {
                    //打开对应的软件名称
                    SubKey = Key32.OpenSubKey(SubKeyName);
                    if (SubKey != null)
                    {
                        DisplayName = SubKey.GetValue("DisplayName", "Nothing").ToString();                        
                        //如果没有取到,则不存入动态数组
                        if (DisplayName != "Nothing")
                        {
                            infor.Append("<App32 id=\\"" + i.ToString() + "\\">");
                            infor.Append("<AppName32>" + DisplayName + "</AppName32>");
                            Path = SubKey.GetValue("InstallLocation", "").ToString();
                            if (string.IsNullOrEmpty(Path))
                            {
                                Path = SubKey.GetValue("DisplayIcon","").ToString();
                            }
                            infor.Append("<Path32>" + Path + "</Path32>");
                            infor.Append("</App32>");
                        }
                        i++;
                    }
                }
                infor.Append("</Win32App>");
            }
            #endregion
            return infor.ToString();            
        }

  获取所有进程 (任务管理器里面的进程和和任务管理器应用程序中任务对应的进程区分开来)

            #region 获取所有进程
            string processInfor = GetAllProcessInfor();
            #endregion
        /// <summary>
        /// 获取所有进程信息
        /// </summary>
        /// <returns></returns>
        private string GetAllProcessInfor()
        {
            StringBuilder infor=new StringBuilder();
            StringBuilder backPro = new StringBuilder();
            StringBuilder taskPro = new StringBuilder();
            Process[] myProcesses = Process.GetProcesses();
            string path = "";  //进程路径
            string name = "";  //进程名称
            string program = "";  //进程程序
            string proUserName = ""; //进程用户名
            int i = 0;
            int j = 0;
            foreach (var process in myProcesses)
            {
                if (process.MainWindowHandle != null && !string.IsNullOrEmpty(process.MainWindowTitle))
                {
                    #region 任务进程
                    try
                    {
                        j++;
                        taskPro.Append("<TaskPro id=\\"" + j.ToString() + "\\">");
                        name = process.ProcessName;
                        taskPro.Append("<name>" + name + "</name>");
                        proUserName = GetProcessUserName(process.Id);
                        taskPro.Append("<userName>" + proUserName + "</userName>");
                        taskPro.Append("<mainWindowTitle>" + process.MainWindowTitle + "</mainWindowTitle>");
                        program = process.MainModule.ModuleName.ToString();
                        taskPro.Append("<program>" + program + "</program>");
                        path = process.MainModule.FileName.ToString();
                        taskPro.Append("<path>" + path + "</path>");
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        taskPro.Append("</TaskPro>");
                    }
                    #endregion
                }
                else
                {
                    #region 后台进程
                    try
                    {
                        i++;
                        backPro.Append("<BackPro id=\\"" + i.ToString() + "\\">");
                        name = process.ProcessName;
                        backPro.Append("<name>" + name + "</name>");
                        proUserName = GetProcessUserName(process.Id);
                        backPro.Append("<userName>" + proUserName + "</userName>");
                        program = process.MainModule.ModuleName.ToString();
                        backPro.Append("<program>" + program + "</program>");
                        path = process.MainModule.FileName.ToString();
                        backPro.Append("<path>" + path + "</path>");
                    }
                    catch (Exception ex)
                    {
                    }
                    finally
                    {
                        backPro.Append("</BackPro>");
                    }
                    #endregion
                }
                
            }
            infor.Append("<TaskProcess>" + taskPro.ToString() + "</TaskProcess>");            
            infor.Append("<BackProcess>" + backPro.ToString() + "</BackProcess>");
            return infor.ToString();
        }

 获取所有服务

            #region 所有服务
            string serviceInfor = GetAllServiceInfor();
            #endregion  
        /// <summary>
        /// 获取服务信息
        /// </summary>
        /// <returns></returns>
        private string GetAllServiceInfor()
        {
            StringBuilder infor = new StringBuilder();
            string serviceName = "";
            string path = "";
            string description = "";
            ServiceController[] services = System.ServiceProcess.ServiceController.GetServices();
            long serverID = 1;
            foreach (var ser in services)
            {
                infor.Append("<Service serverID=\\"" + serverID.ToString() + "\\">");
                serviceName = ser.DisplayName;
                if (serviceName.Contains("&"))
                {
                    serviceName = serviceName.Replace("&", "<");
                }
                infor.Append("<ServiceName>" + serviceName + "</ServiceName>");
                path = ServerFilePathAndDescription(ser.ServiceName, out description);
                infor.Append("<Path>" + path + "</Path>");
                infor.Append("<Description>" + description + "</Description>");
                infor.Append("</Service>");
                //infor = infor + serviceName + "," + path + "," + description + "&";
                serverID++;
            }
            return infor.ToString();
        }

        /// <summary>
        /// 通过服务名称获取服务路径和服务描述
        /// </summary>
        /// <param name="serviceName">服务名称</param>
        /// <param name="description">服务描述</param>
        /// <returns></returns>
        public string ServerFilePathAndDescription(string serviceName, out string description)
        {
            description = "";
            RegistryKey _Key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\ControlSet001\\Services\\" + serviceName);
            if (_Key != null)
            {
                object _ObjDescription = _Key.GetValue("Description");
                if (_ObjDescription != null) description = _ObjDescription.ToString();
                object _ObjPath = _Key.GetValue("ImagePath");
                if (_ObjPath != null) return _ObjPath.ToString();
            }
            return "";
        }

 硬盘序列号

        /// <summary>
        /// 获取硬盘ID
        /// </summary>
        /// <returns></returns>
        public static string GetHardDisId()
        {
            try
            {
                ManagementClass mClass = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mClass.GetInstances();
                string HDid = "";
                foreach (ManagementObject mo in moc)
                {
                    HDid = HDid + mo.Properties["Model"].Value.ToString() + "  ,";
                    mo.Dispose();
                }
                moc.Dispose();
                mClass.Dispose();
                HDid = HDid.Substring(0, HDid.Length - 1);
                return HDid;

            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

 主板编号

        /// <summary>
        /// 主板编号
        /// </summary>
        /// <returns></returns>
        public static string GetBaseboardId()
        {
            try
            {
                ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");
                string BBid = "";
                foreach (ManagementObject mo in mos.Get())
                {
                    BBid = BBid + mo["SerialNumber"].ToString() + "  ,";
                    mo.Dispose();
                }
                mos.Dispose();

                BBid = BBid.Substring(0, BBid.Length - 1);
                return BBid;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

 

   整理的基本上就这些了,如有不足之处,希望大家多多指正!谢谢

以上是关于C# 获取本机mac地址 客户端主机名称(hostName) 当前用户(CurWinUser) 操作系统版本(WinVersion) IE浏览器版本(IEversion) 物理内存(Memo的主要内容,如果未能解决你的问题,请参考以下文章

C# 获取本机CPU序列号,MAC地址,硬盘ID,本机IP地址,计算机名,物理内存,PC类型

C#获取本机信息(本机名称,系统版本号,联网状态,IP地址)

C# 获取MAC地址

java如何查询本机ip地址和mac地址

QT获取本机IP和Mac地址

一个基于C#编写的基础网络信息检测工具