用程序获取本机IP地址,mac地址

1.获取本机ip地址

  // 定义要返回的Ip地址.
            string strIpAddress = string.Empty;

            try
            {
                foreach (IPAddress ipAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                {
                    if (ipAddress.AddressFamily.ToString() == "InterNetwork")
                    {
                        strIpAddress = ipAddress.ToString();
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // Ip地址获取失败.
                LogHelper.WriteLog("Ip地址获取失败", e);
            }

            // 返回Ip地址.
            return strIpAddress;

2. 获取本机mac地址(联网有效,断网失效)

       // 定义要返回的Mac地址.
            string strMacAddress = string.Empty;
           try
            {
                // 实例化公共信息模型管理类.
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration" );
                // 取得该类的所有实例集合.
                ManagementObjectCollection moc = mc.GetInstances();

                // 遍历实例集合.
                foreach ( var o in moc)
                {
                    var mo = o as ManagementObject;
                    if (mo != null && ( bool)mo[ "IPEnabled"])
                    {
                        // 取得Mac地址.
                        strMacAddress = mo[ "MacAddress"].ToString().Replace(':' , '-' );
                        // 结束循环.
                        break;
                    }
                }
            }
            catch ( Exception e)
            {
                // Mac地址获取失败.
                LogHelper.WriteLog( "Mac地址获取失败" , e);
            }

3.获取本机mac地址(断网有效-通过cmd命令获取)

  List< string> macs = new List< string>();
            ProcessStartInfo startInfo = new ProcessStartInfo ("ipconfig" , "/all" );
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.CreateNoWindow = true;
            Process p = Process.Start(startInfo);
            //截取输出流
            StreamReader reader = p.StandardOutput;
            string line = reader.ReadLine();

            while (!reader.EndOfStream)
            {
                if (! string.IsNullOrEmpty(line))
                {
                    line = line.Trim();

                    if (line.StartsWith( "物理地址" ))
                    {
                        //等待程序执行完退出进程
                        p.WaitForExit();
                        p.Close();
                        reader.Close();

                        return line.Substring(line.IndexOf( ":") + 1);
                    }
                }
                line = reader.ReadLine();
            }



你可能感兴趣的:(C#)