C#获取IP和默认网关

 

 

        static void Main(string[] args)
        {
            string mac=null,ip=null,ipsubnet=null,ipgateway=null,ipport=null;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection nics = mc.GetInstances();
            foreach (ManagementObject nic in nics)
            {
                if ((nic["DefaultIPGateway"] as String[]) != null && Convert.ToBoolean(nic["ipEnabled"]) == true)
                {
                    mac = nic["MacAddress"].ToString();//Mac地址
                    ip = (nic["IPAddress"] as String[])[0];//IP地址
                    ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码
                    ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关
                }
            }
            Console.WriteLine(mac);
            Console.WriteLine(ip);
            Console.WriteLine(ipsubnet);
            Console.WriteLine(ipgateway);
            Console.ReadKey();

        }

 

posted @ 2021-10-21 22:44  bingxingc  阅读(604)  评论(0编辑  收藏  举报