获取本地内网和外网IP地址

public class IPUtil
    {
        /// <summary>
        /// 获取本地内网IP
        /// </summary>
        /// <returns></returns>
        public string GetHostIPAddress()
        {
            try
            {
                IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                foreach (IPAddress item in ipEntry.AddressList)
                {
                    if (item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        string ip = item.ToString();
                        return ip;
                    }
                }

                return String.Empty;
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }

        /// <summary>
        /// 获取本地外网IP
        /// </summary>
        /// <returns></returns>
        public static string GetExtranetIPAddress()
        {
            try
            {
                string ip = String.Empty;
                System.Net.WebRequest request = System.Net.WebRequest.Create("http://www.ip138.com/ip2city.asp");
                using (System.Net.WebResponse response = request.GetResponse())
                using (System.IO.StreamReader stream = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    string result = stream.ReadToEnd();
                    string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
                    ip = Regex.Match(result, pattern, RegexOptions.IgnoreCase).ToString();
                }

                return ip;
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }
    }

 

posted @ 2016-11-14 17:12  Plus301  阅读(1167)  评论(0编辑  收藏  举报