获取IP地址-根据IP获取位置信息

获取外网IP地址,并得到该地址所在位置;

如:101.249.255.255

对应:西藏自治区-拉萨市-堆龙德庆区

string ipAddress = GetIPAddress();
string location = GetIPLocation(ipAddress);
        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {
            try
            {
                //此接口查询速度最快
                var html2 = HttpGetPageHtml("http://www.net.cn/static/customercare/yourip.asp", "gbk");
                var ip2 = GetIPFromHtml(html2);
                if (!String.IsNullOrEmpty(ip2)) return ip2;

                return "";
            }
            catch (System.Exception ex)
            {
                mzRunLog.RunlogDebug ("获取IP地址错误:" + ex.Message);
                return "";
            }
        }

        /// <summary>
        /// 根据IP获取我们所要的信息
        /// </summary>
        /// <param name="strIp"></param>
        /// <returns></returns>
        public static string GetIPLocation(string strIp)
        {
            try
            {
                if (strIp == "")
                    return "";
                string html = HttpGetPageHtml("https://www.ip138.com/iplookup.asp?ip=" + strIp + "&action=2", "gb2312");
                string pre = "var ip_result = {\"ASN归属地\":\"";
                int pos = html.IndexOf(pre);
                html = html.Substring(pos + pre.Length);
                html = html.Substring(0, html.IndexOf(' ')).Replace("移动", "").Replace("联通", "").Replace("电信", "");
                //string[] res = html.Split(new char[] { '省', '市', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                String regex = "(?<province>[^省]+省|.+自治区)(?<city>[^自治州]+自治州|[^市]+市|[^盟]+盟|[^地区]+地区|.+区划)(?<county>[^市]+市|[^县]+县|[^旗]+旗|.+区)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
                // 使用正则表达式匹配省、市、区、镇和村
                Match match = Regex.Match(html, regex);
                if (match.Success)
                {
                    string province = match.Groups["province"].Value;
                    string city = match.Groups["city"].Value;
                    string county = match.Groups["county"].Value;
                    //string town = match.Groups["town"].Value;
                    //string village = match.Groups["village"].Value;

                    //Console.WriteLine("省:" + province);
                    //Console.WriteLine("市:" + city);
                    //Console.WriteLine("区/县:" + county);
                    //Console.WriteLine("镇:" + town);
                    //Console.WriteLine("村/街道:" + village);
                    return city;
                }

                return "";
            }
            catch (System.Exception ex)
            {
                mzRunLog.RunlogDebug("获取位置信息错误:" + ex.Message);
                return "";
            }

        }

 获取网页信息,解析获取网页中IP地址

        /// <summary>
        /// 获取页面html
        /// </summary>
        /// <param name="url">请求的地址</param>
        /// <param name="encoding">编码方式</param>
        /// <returns></returns>
        private static string HttpGetPageHtml(string url, string encoding)
        {
            string pageHtml = string.Empty;
            try
            {
                using (WebClient MyWebClient = new WebClient())
                {
                    Encoding encode = Encoding.GetEncoding(encoding);
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                    Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                    pageHtml = encode.GetString(pageData);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return pageHtml;
        }
        /// <summary>
        /// 从html中通过正则找到ip信息(只支持ipv4地址)
        /// </summary>
        /// <param name="pageHtml"></param>
        /// <returns></returns>
        private static string GetIPFromHtml(String pageHtml)
        {
            //验证ipv4地址
            string reg = @"(?:(?:(25[0-5])|(2[0-4]\d)|((1\d{2})|([1-9]?\d)))\.){3}(?:(25[0-5])|(2[0-4]\d)|((1\d{2})|([1-9]?\d)))";
            string ip = "";
            Match m = Regex.Match(pageHtml, reg);
            if (m.Success)
            {
                ip = m.Value;
            }
            return ip;
        }

参考:

.Net/C# --- 根据Ip获取地址信息

正则表达式 划分省市区(直辖市和附详细地址包括市,区)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值