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());
                    }
                }
            }
        }




原文地址:https://www.cnblogs.com/lcchuguo/p/4823922.html