C#以太网IP、wlanIP、虚拟机IP这三个IP怎样获取指定IP呢

2024-12-17 08:33:48
推荐回答(1个)
回答1:

 /// 
        /// 获取网络相关信息
        /// 

        /// 
        public List GetNetInfo()
        {
            List netList = new List();
            try
            {
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection nics = mc.GetInstances();
                foreach (ManagementObject nic in nics)
                {
                    if (Convert.ToBoolean(nic["ipEnabled"]) == true)
                    {
                        string ip = (nic["IPAddress"] as String[])[0];//IP地址    
                        string ipsubnet = (nic["IPSubnet"] as String[])[0];//子网掩码     
                        string ipgateway = (nic["DefaultIPGateway"] as String[])[0];//默认网关  
                        string mac = nic["MacAddress"].ToString();//Mac地址
                        string[] dns = (string[])(nic["DNSServerSearchOrder"]);//DNS地址(首选、备用)
                        netList.Add(ip);
                        netList.Add(ipsubnet);
                        netList.Add(ipgateway);
                        netList.Add(mac);
                        netList.Add(dns[0]);
                        netList.Add(dns[1]);
                        break;
                    }
                }
                return netList;
            }
            catch
            {
                return netList;
            }
        }
        
        ///  
        /// 获取外网IP 
        /// 
 
        ///  
        private static string GetIP()
        {
            string tempip = "";
            try
            {
                WebRequest wr = WebRequest.Create("http://www.ip138.com/ips138.asp");
                Stream s = wr.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                string all = sr.ReadToEnd(); //读取网站的数据
                int start = all.IndexOf("您的IP地址是:[") + 9;
                int end = all.IndexOf("]", start);
                tempip = all.Substring(start, end - start);
                sr.Close();
                s.Close();
            }
            catch
            {
            }
            return tempip;
        }