首页 > 代码库 > 13 在C#中如何获得IP地址

13 在C#中如何获得IP地址

首先需要添加命名空间
using System.Net.NetworkInformation;
using System.Net.Sockets;

下面是详细代码

        GetPrivateIP();
        string publicIP = GetPublicIP();
        Console.WriteLine("Public IP is: {0}", publicIP);
			
		//获取公共网络IP地址
        static string GetPublicIP()
        {
            String address = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                address = stream.ReadToEnd();
            }

            // 从html页面中查找IP地址
            int first = address.IndexOf("Address: ") + 9;
            int last = address.LastIndexOf("</body>");
            address = address.Substring(first, last - first);

            return address;
        }
		//获取私有IP地址
		static void GetPrivateIP()
        {
            
            foreach (var interfaces in NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (var address in interfaces.GetIPProperties().UnicastAddresses)
                {
                    if (address.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        Console.WriteLine("IP Address:  " + address.Address.ToString());
                    }
                }
            }
        }