C# 取到本机IP地址和公网IP地址

最近在项目中要用到电脑的IP地址整理两个方法记录一下。

        /// 
        /// 本机IPv4IP地址
        /// 
        /// 本机IPv4IP地址
        public string GetIPv4Address()
        {
            string ip=string.Empty;
            try
            {
                string HostName = Dns.GetHostName();
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                foreach (IPAddress ipAddress in IpEntry.AddressList)
                {
                    if (ipAddress .AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        ip= ipAddress.ToString();
                    }
                }
            }
            catch
            {
                return "unknown";
            }
            return ip;
        }
        /// 
        /// 获取本机公网IP地址
        /// 
        private string GetInternetAddress()
        {
            string ip = "";
            try
            {
                WebRequest wr = WebRequest.Create("http://2019.ip138.com/ic.asp");
                Stream s = wr.GetResponse().GetResponseStream();
                StreamReader sr = new StreamReader(s, Encoding.Default);
                string all = sr.ReadToEnd(); //读取网站的数据

                int start = all.IndexOf("[") + 1;//指定字符在字符串中的索引
                int end = all.IndexOf("]", start);
                ip = all.Substring(start, end - start);
                sr.Close();
                s.Close();
                return ip;
            }
            catch
            {
                return "unknown";
            }
        }

结果:

C# 取到本机IP地址和公网IP地址_第1张图片

你可能感兴趣的:(C#,方法)