Windows上獲得IP地址的四種方法

來源:互聯網
上載者:User
最近在看網路編程(主要是TCP/IP通訊的)的內容,還研究了下WMI。把獲得IP地址的方法總結如下。1.      使用ipconfig程式。在命令列下使用命令ipconfig可以得到原生每個有效網羅介面的IP網絡資訊。如果在代碼中,可以使用Process.Start()方法來調用ipconfig,然後使用Regex來解析結果──當然這樣做太繁了,不實用。但我曾經使用類似的方法在代碼中獲得MAC地址。2.      尋找註冊表。使用註冊表的麻煩之處在於各個版本的Windows在不同的地方存放網絡資訊。 Windows98&Windows Me註冊表中的位置為:          HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Class\NetTrans在這下面,每個Key對應一個網路裝置的資訊(IPAddress,DefaultGateway,IPMask)。   Windows NT Windows 2000&Windows XP  和Windows98,Me不同,先要得知有哪些網卡,然後再查此網卡的網絡資訊。第一步:找到網卡,地址為:HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\NetworkCards,從中得到ServiceName值;第二步:根據上面得到的ServiceName值到下面地址尋找:HKEY_LOCAL_MACHINE\CurrentControlSet\Services,找到響應的Key後,在parameters\tcpip下可以得到網路裝置的資訊(IPAddress,DefaultGateway,IPMask)。另外,對於動態IP地址,可能得去尋找DHCPIPAddress註冊表對應關鍵詞的值。3.      使用WMI。查詢表Win32_NetworkAdapterConfiguration即可獲得。4.      使用DNS。 

代碼如下:using System;
using Microsoft.Win32;
using System.Management;
using System.Net;
namespace IPAddress
{
    class MainClass
    {
        /**//// <summary>
        /// 應用程式的主進入點。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            GetIPByRegistry();
            GetIPByWMI();
            GetIPByDns();
            Console.ReadLine();
        }

        Methods#region Methods
        private const string CARDKEY = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards";
        private const string SERVICEKEY = @"SYSTEM\CurrentControlSet\Services\";
        public static void GetIPByRegistry()
        {
            RegistryKey entry = Registry.LocalMachine;
            RegistryKey services = entry.OpenSubKey(CARDKEY);
            if ( services == null)
                return;

            string[] cards = services.GetSubKeyNames();
            services.Close();

            foreach (string key in cards )
            {
                RegistryKey cardService = entry.OpenSubKey(CARDKEY + "\\" +key);
                if ( cardService == null )
                    return;
                string serviceName = cardService.GetValue("ServiceName").ToString();
                Console.WriteLine("\n Network card : {0}",serviceName);
                
                RegistryKey networkCard = entry.OpenSubKey(SERVICEKEY+serviceName+"\\Parameters\\Tcpip");
                if ( networkCard != null )
                {
                    string[] ips = (string[]) networkCard.GetValue("IPAddress");
                    foreach ( string ip in ips)
                    {
                        Console.WriteLine(" The IPAddress is  :{0}",ip);
                    }
                    networkCard.Close();
                }
                entry.Close();
            }
        }

        public static void GetIPByWMI()
        {
            string query = "select IPAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection collection = searcher.Get();
            foreach ( ManagementObject mo in collection )
            {
                string[] ips = (string[])mo["IPAddress"];
                foreach ( string ip in ips )
                {
                    Console.WriteLine(" Network card ip is :{0}",ip);
                }
            }
        }

        public static void GetIPByDns()
        {
            System.Net.IPAddress[] ips = Dns.GetHostByName(Dns.GetHostName()).AddressList;
            foreach ( System.Net.IPAddress ip in ips )
            {
                Console.WriteLine("The ip is : {0}",ip.ToString());
            }
        }
        #endregion
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.