ASP.NET Ajax 获取IP地理位置

介绍
本文使用Ajax技术获取IP地理位置,这里的IP地理位置是通过抓取第三方网站的内容获取的。
 
解决方案
我们使用这样的方式获取IP所在的地理位置

http://dev.mjxy.cn/ajaxcheck.aspx?action=getip&ip=202.96.64.68&ipurl=http%3A//www.ip138.com/ips.asp%3Fip%3D&startstr=%u672C%u7AD9%u4E3B%u6570%u636E%uFF1A&endstr=%3C/li%3E%3Cli%3E%u53C2%u8003%u6570%u636E
 

下面是未经过url编码的参数值

action="getip"
ip="202.96.64.68"
ipurl = "http://www.ip138.com/ips.asp?ip="
startStr="本站主数据:"
endStr="</li><li>参考数据"
 

将这些值传递给ajaxcheck.aspx页面,通过后台代码下载ip138.com 返回的网页数据,然后在采集 startStr和endStr之间的内容并直接返回结果。startStr和endStr之间的内容就是我们需要的IP的地理位置。你可以通过观察http://www.ip138.com/ips.asp?ip=202.96.64.68的网页源代码了解。
 
 
代码示例
服务器端代码ajaxcheck.aspx.cs

    public partial class AjaxCheck : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (action == "getip")
            {
                string ip = Request["ip"]; //ip地址
                string ipurl = Server.UrlDecode(Request["ipurl"]); //获取ip的url
                string startStr = Server.UrlDecode(Request["startstr"]); //开始字符串
                string endStr = Server.UrlDecode(Request["endStr"]); //结束字符
                Response.Write(GetIPFrom(ipurl, ip,startStr , endStr));
            }
 
            Response.End();
        }
 
        /// <summary>
        /// 网页抓取ip地址所在地
        /// </summary>
        /// <param name="getIpUrl">//获取ip的url</param>
        /// <param name="ip">ip地址</param>
        /// <param name="startStr">开始字符串</param>
        /// <param name="endStr">结束字符串</param>
        /// <returns></returns>
        public string GetIPFrom(string getIpUrl,string ip,string startStr,string endStr)
        {
    //创建Request访问
            HttpWebRequest httpWebRequest =
                  (HttpWebRequest)WebRequest.Create(getIpUrl + ip);
            //设置访问头
            httpWebRequest.Accept = "*/*";
            httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; CNCDialer; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            //获取Response
            HttpWebResponse httpWebResponse =
                    (HttpWebResponse)httpWebRequest.GetResponse();
            //编码检测
    string contentType = httpWebResponse.ContentType;
            int pos = contentType.IndexOf("t=");
            if (pos == -1)
                contentType = "gb2312";
            else
                contentType = contentType.Substring(pos + 2);
            //获取网页内容
            Stream stream = httpWebResponse.GetResponseStream();
            StreamReader streamReader =
               new StreamReader(stream, Encoding.GetEncoding(contentType));
            string html = streamReader.ReadToEnd();
 
            //采集内容
            //查找起点
            int startPos = html.IndexOf(startStr);
            string ipName = "";
            if (startPos > 0)
            {
                ipName = html.Substring(startPos + startStr.Length);//截断找到位置之前的内容
                int endPos = ipName.IndexOf(endStr);
                if (endPos > 0)
                {
                    ipName = ipName.Remove(endPos); //删除结束点之后的内容
                }
                else
                {
                    return "not found!";
                }
            }
            else
            {
                return "not found!";
            }
            return ipName; //返回采集结果
        }
    }
 

客户端部分
假设页面上有如下内容:

<a href="#" class="clientip">202.96.64.68</a>

我们使用JQuery来操作clientip,当单击的时候获取ip地址的地址位置并用对话框显示。代码如下:

$(document).ready(function () {
    $('.clientip').click(function () {
        try {
            var ipaddress = $(this).html(); //get ip address
            var ip_url = escape("http://www.ip138.com/ips.asp?ip=");
            var start_str = escape("本站主数据:");
            var end_str = escape("</li><li>参考数据");
            jQuery.get("AjaxCheck.aspx", { action: 'getip', ip: ipaddress, ipurl: ip_url, startStr: start_str, endStr: end_str }, function (data) {
                alert(ipaddress + ":" + data);
            });
        } catch (err) { }
    });
});
 

还可以使用下面的方法获取数据

ar str = $.ajax({ url: "AjaxCheck.aspx", data: { action: 'getip', ip: ipaddress, ipurl: ip_url, startStr: start_str, endStr: end_str, async: false }, type: 'GET', async: false, cache: false }).responseText;
alert(str);

你可以查看 http://dev.mjxy.cn/faqs.aspx 就是利用这种方式实现的获取IP地址位置。

参考资料

下载网页输出到控制台  http://dev.mjxy.cn/a-Download-the-page-output-to-the-console.aspx

posted @ 2011-08-17 06:47  敏捷学院  阅读(3827)  评论(0编辑  收藏  举报