xml-asp获取IP归属地怎么实现?

问题描述

asp获取IP归属地怎么实现?

在网上搜索了一下,获取客户端的访问IP,这个会。
但是如何查询出该IP的归属地如何实现?

网上提供了IP地址归属地查询接口,有返回json的,有返回xml的,有返回文本的。
不知道怎么使用。写的都比较简单。

能否运用到asp里面?能否提供一个比较完整的查询接口,可以查询归属地、ISP等信息的。
然后插入到数据库里。
能否举个详细的例子。谢谢。

解决方案

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
public class IPHelper
{
//IP来源地(传入的是 IP地址 例 127.0.0.1)
public static string GetIpAdderss(object obj)
{
try
{
string objs = obj as string;
QQWryLocator qqWry = new QQWryLocator(new Page().Server.MapPath("~/upload/QQWry/QQWry.Dat")); //这个文件网上有下载
IPLocation ip = qqWry.Query(objs);
return ip.Country + objs;
}
catch
{
return "本地";
}
}

public class IPLocation
{
    private string _IP;
    private string _Country;
    private string _Local;
    public string IP
    {
        get { return _IP; }
        set { _IP = value; }
    }
    public string Country
    {
        get { return _Country; }
        set { _Country = value; }
    }
    public string Local
    {
        get { return _Local; }
        set { _Local = value; }
    }
}
public class QQWryLocator
{
    private byte[] data;
    Regex regex = new Regex(@"(((d{1,2})|(1d{2})|(2[0-4]d)|(25[0-5])).){3}((d{1,2})|(1d{2})|(2[0-4]d)|(25[0-5]))");
    long firstStartIpOffset;
    long lastStartIpOffset;
    long ipCount;
    public long Count { get { return ipCount; } }
    public QQWryLocator(string dataPath)
    {
        using (FileStream fs = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);
        }
        byte[] buffer = new byte[8];
        Array.Copy(data, 0, buffer, 0, 8);
        firstStartIpOffset = ((buffer[0] + (buffer[1] * 0x100)) + ((buffer[2] * 0x100) * 0x100)) + (((buffer[3] * 0x100) * 0x100) * 0x100);
        lastStartIpOffset = ((buffer[4] + (buffer[5] * 0x100)) + ((buffer[6] * 0x100) * 0x100)) + (((buffer[7] * 0x100) * 0x100) * 0x100);
        ipCount = Convert.ToInt64((double)(((double)(lastStartIpOffset - firstStartIpOffset)) / 7.0));
        if (ipCount <= 1L)
        {
            throw new ArgumentException("ip FileDataError");
        }
    }
    private static long IpToInt(string ip)
    {
        char[] separator = new char[] { '.' };
        if (ip.Split(separator).Length == 3)
        {
            ip = ip + ".0";
        }
        string[] strArray = ip.Split(separator);
        long num2 = ((long.Parse(strArray[0]) * 0x100L) * 0x100L) * 0x100L;
        long num3 = (long.Parse(strArray[1]) * 0x100L) * 0x100L;
        long num4 = long.Parse(strArray[2]) * 0x100L;
        long num5 = long.Parse(strArray[3]);
        return (((num2 + num3) + num4) + num5);
    }
    private static string IntToIP(long ip_Int)
    {
        long num = (long)((ip_Int & 0xff000000L) >> 0x18);
        if (num < 0L)
        {
            num += 0x100L;
        }
        long num2 = (ip_Int & 0xff0000L) >> 0x10;
        if (num2 < 0L)
        {
            num2 += 0x100L;
        }
        long num3 = (ip_Int & 0xff00L) >> 8;
        if (num3 < 0L)
        {
            num3 += 0x100L;
        }
        long num4 = ip_Int & 0xffL;
        if (num4 < 0L)
        {
            num4 += 0x100L;
        }
        return (num.ToString() + "." + num2.ToString() + "." + num3.ToString() + "." + num4.ToString());
    }
    public IPLocation Query(string ip)
    {
        if (!regex.Match(ip).Success)
        {
            throw new ArgumentException("IP格式错误");
        }
        IPLocation ipLocation = new IPLocation();
        ipLocation.IP = ip;
        long intIP = IpToInt(ip);
        if ((intIP >= IpToInt("127.0.0.1") && (intIP <= IpToInt("127.255.255.255"))))
        {
            ipLocation.Country = "本机内部环回地址";
            ipLocation.Local = "";
        }
        else
        {
            if ((((intIP >= IpToInt("0.0.0.0")) && (intIP <= IpToInt("2.255.255.255"))) || ((intIP >= IpToInt("64.0.0.0")) && (intIP <= IpToInt("126.255.255.255")))) ||
            ((intIP >= IpToInt("58.0.0.0")) && (intIP <= IpToInt("60.255.255.255"))))
            {
                ipLocation.Country = "网络保留地址";
                ipLocation.Local = "";
            }
        }
        long right = ipCount;
        long left = 0L;
        long middle = 0L;
        long startIp = 0L;
        long endIpOff = 0L;
        long endIp = 0L;
        int countryFlag = 0;
        while (left < (right - 1L))
        {
            middle = (right + left) / 2L;
            startIp = GetStartIp(middle, out endIpOff);
            if (intIP == startIp)
            {
                left = middle;
                break;
            }
            if (intIP > startIp)
            {
                left = middle;
            }
            else
            {
                right = middle;
            }
        }
        startIp = GetStartIp(left, out endIpOff);
        endIp = GetEndIp(endIpOff, out countryFlag);
        if ((startIp <= intIP) && (endIp >= intIP))
        {
            string local;
            ipLocation.Country = GetCountry(endIpOff, countryFlag, out local);
            ipLocation.Local = local;
        }
        else
        {
            ipLocation.Country = "未知";
            ipLocation.Local = "";
        }
        return ipLocation;
    }
    private long GetStartIp(long left, out long endIpOff)
    {
        long leftOffset = firstStartIpOffset + (left * 7L);
        byte[] buffer = new byte[7];
        Array.Copy(data, leftOffset, buffer, 0, 7);
        endIpOff = (Convert.ToInt64(buffer[4].ToString()) + (Convert.ToInt64(buffer[5].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[6].ToString()) * 0x100L) * 0x100L);
        return ((Convert.ToInt64(buffer[0].ToString()) + (Convert.ToInt64(buffer[1].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[2].ToString()) * 0x100L) * 0x100L)) + (((Convert.ToInt64(buffer[3].ToString()) * 0x100L) * 0x100L) * 0x100L);
    }
    private long GetEndIp(long endIpOff, out int countryFlag)
    {
        byte[] buffer = new byte[5];
        Array.Copy(data, endIpOff, buffer, 0, 5);
        countryFlag = buffer[4];
        return ((Convert.ToInt64(buffer[0].ToString()) + (Convert.ToInt64(buffer[1].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[2].ToString()) * 0x100L) * 0x100L)) + (((Convert.ToInt64(buffer[3].ToString()) * 0x100L) * 0x100L) * 0x100L);
    }
    /// <summary>
    /// Gets the country.
    /// </summary>
    /// <param name="endIpOff">The end ip off.</param>
    /// <param name="countryFlag">The country flag.</param>
    /// <param name="local">The local.</param>
    /// <returns>country</returns>
    private string GetCountry(long endIpOff, int countryFlag, out string local)
    {
        string country = "";
        long offset = endIpOff + 4L;
        switch (countryFlag)
        {
            case 1:
            case 2:
                country = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
                offset = endIpOff + 8L;
                local = (1 == countryFlag) ? "" : GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
                break;
            default:
                country = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
                local = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
                break;
        }
        return country;
    }
    private string GetFlagStr(ref long offset, ref int countryFlag, ref long endIpOff)
    {
        int flag = 0;
        byte[] buffer = new byte[3];
        while (true)
        {
            //用于向前累加偏移量
            long forwardOffset = offset;
            flag = data[forwardOffset++];
            //没有重定向
            if (flag != 1 && flag != 2)
            {
                break;
            }
            Array.Copy(data, forwardOffset, buffer, 0, 3);
            forwardOffset += 3;
            if (flag == 2)
            {
                countryFlag = 2;
                endIpOff = offset - 4L;
            }
            offset = (Convert.ToInt64(buffer[0].ToString()) + (Convert.ToInt64(buffer[1].ToString()) * 0x100L)) + ((Convert.ToInt64(buffer[2].ToString()) * 0x100L) * 0x100L);
        }
        if (offset < 12L)
        {
            return "";
        }
        return GetStr(ref offset);
    }
    private string GetStr(ref long offset)
    {
        byte lowByte = 0;
        byte highByte = 0;
        StringBuilder stringBuilder = new StringBuilder();
        byte[] bytes = new byte[2];
        Encoding encoding = Encoding.GetEncoding("GB2312");
        while (true)
        {
            lowByte = data[offset++];
            if (lowByte == 0)
            {
                return stringBuilder.ToString();
            }
            if (lowByte > 0x7f)
            {
                highByte = data[offset++];
                bytes[0] = lowByte;
                bytes[1] = highByte;
                if (highByte == 0)
                {
                    return stringBuilder.ToString();
                }
                stringBuilder.Append(encoding.GetString(bytes));
            }
            else
            {
                stringBuilder.Append((char)lowByte);
            }
        }
    }
}

}

调用方式:
protected void Page_Load(object sender, EventArgs e)
{
//只看这一句就行了
string ip归属地 = IPHelper.GetIpAdderss("112.111.188.102");
string userName = "0t51pqq";
bool isBad = Regex.IsMatch(userName, @"^[0-9A-Za-z]{8,}$")&&(ip归属地.LastIndexOf("福建") != -1);
if (isBad)
{
Response.Write("alert('普通注册正在维护,请使用QQ登录(论坛首页右上角)。');window.location.href='/'");
}
else
{
Response.Write(ip归属地);
}
}

解决方案二:

http://download.csdn.net/detail/wang__wei/5233065 这儿是个下载的地址,不过我没仔细看代码,你也可以看一下,希望对你有用

解决方案三:

可以使用xmlhttp访问www.ip138.com获取。参考:http://zhidao.baidu.com/link?url=0QSopInE-8h4vQMkw78yGrFBU4mVdnFW4-4ngU4y9plCJpMCtnSnvESQMISqSzeY39yLl73gDnQ6XPo-MZutUa

解决方案四:

新浪的IP地址查询接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js ==》这个是访问者的
新浪多地域测试方法:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.192.3.42 ==》 这个查询指定ip的
var remote_ip_info = {"ret":1,"start":"116.1.29.0","end":"116.1.43.255","country":"u4e2du56fd","province":"u5e7fu897f","city":"u6842u6797","district":"u4e03u661f","isp":"u7535u4fe1","type":"","desc":""};
var returnCitySN = {"cip": "116.1.39.88", "cid": "450300", "cname": "广西壮族自治区桂林市"};

搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/cityjson?ie=utf-8

demo

window.onload = function () {
document.body.appendChild(document.createTextNode('['+returnCitySN.cname+"]的朋友,您好!"));
}

搜狐IP地址查询接口(默认GBK):http://pv.sohu.com/cityjson

解决方案五:

新浪的IP地址查询接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js ==》这个是访问者的
新浪多地域测试方法:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=218.192.3.42 ==》 这个查询指定ip的
var remote_ip_info = {"ret":1,"start":"116.1.29.0","end":"116.1.43.255","country":"u4e2du56fd","province":"u5e7fu897f","city":"u6842u6797","district":"u4e03u661f","isp":"u7535u4fe1","type":"","desc":""};
var returnCitySN = {"cip": "116.1.39.88", "cid": "450300", "cname": "广西壮族自治区桂林市"};

搜狐IP地址查询接口(可设置编码):http://pv.sohu.com/cityjson?ie=utf-8

demo

window.onload = function () {
document.body.appendChild(document.createTextNode('['+returnCitySN.cname+"]的朋友,您好!"));
}

搜狐IP地址查询接口(默认GBK):http://pv.sohu.com/cityjson

解决方案六:

这个很简单的吧
比如用百度的查询归属地:
Function getHTTPPage(Path)
t = GetBody(Path)
getHTTPPage=BytesToBstr(t,"GB2312")
End function
Function Newstring(wstr,strng)
Newstring=Instr(lcase(wstr),lcase(strng))
if Newstring<=0 then Newstring=Len(wstr)
End Function
Function BytesToBstr(body,Cset)
dim objstream
set objstream = Server.CreateObject("adodb.stream")
objstream.Type = 1
objstream.Mode =3
objstream.Open
objstream.Write body
objstream.Position = 0
objstream.Type = 2
objstream.Charset = Cset
BytesToBstr = objstream.ReadText
objstream.Close
set objstream = nothing
End Function
Function GetBody(url)
on error resume next
Set Retrieval = CreateObject("Microsoft.XMLHTTP")
With Retrieval
.Open "Get", url, False, "", ""
.Send
GetBody = .ResponseBody
End With
Set Retrieval = Nothing
End Function
url = "http://open.baidu.com/ipsearch/s?wd=$ip&tn=baiduip"
wstr=getHTTPPage(url)
这样把获取到的内容使用正则获取一下就可以了

时间: 2024-12-03 06:28:23

xml-asp获取IP归属地怎么实现?的相关文章

python实现获取Ip归属地等信息_python

如果你有一批IP地址想要获得这些IP具体的信息,比如归属国家,城市等,最好的办法当时是调用现有的api接口来获取,我在之前就写过一篇文章,是关于我的博客被莫名攻击的时,就有获取过一批IP,攻击的时候当时是恢复业务重要,IP该封的就要封,攻击过后这个攻击者的IP信息,自己就可以分析下都来自哪里,有没有什么特征,帮助提示自己网站的安全性,今天这个脚本就是根据提供的IP获得IP归属的具体信息,脚本如下: #!/usr/bin/env python import requests import csv

python获取Ip归属信息的例子

如果你有一批IP地址想要获得这些IP具体的信息,比如归属国家,城市等,最好的办法当时是调用现有的api接口来获取,具体应用场景可以根据自己需要,比如我在之前就写过一篇文章,是关于我的博客被莫名攻击的时,就有获取过一批IP,攻击的时候当然是恢复业务重要,IP该封的就要封,攻击过后这个攻击者的IP信息,自己就可以分析下都来自哪里,有没有什么特征,帮助提示自己网站的安全性,今天这个脚本就是根据提供的IP获得IP归属的具体信息,脚本如下: #!/usr/bin/env python import req

asp获取用户真实IP地址的方法

 一般的程序都具备获取用户IP地址的命令,但是我们访问网站有两种一种是我们这种普通用户,一种是使用代理IP上网的用户,下面我来介绍介绍.   在asp中获取用户IP地址我们最简单的获取方法就是使用  代码如下   Request.ServerVariables("REMOTE_ADDR") 但是如果用户使用了代理服务器IP地址就不对了,但我们可通过  代码如下   Request.ServerVariables("REMOTE_ADDR") 结果上面的两个获取IP的

ASP 获取腾讯IP地址的接口程序代码

<script type=text/javascript教程 src=http://fw.qq.com/ipaddress></script> <script type=text/javascript> var hehe1=IPData[2] var hehe2=IPData[3] alert(hehe1); alert(hehe2); document.write(IPData.join(' ')); </script> 如何用ASP来存储,从上面读取出来

接口-asp获取客户端外网ip(不是192.168形式)

问题描述 asp获取客户端外网ip(不是192.168形式) 服务器上发布了系统,System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString或者System.Web.HttpContext.Current.Request.UserHostAddress;都是得到192.168格式的,我需要得到客户端的对外访问的IP(公司所有同事对外访问的IP都为:180.169.88.9

ASP 获取腾讯IP地址的代码_应用技巧

提问: 复制代码 代码如下: <script type=text/javascript src=http://fw.qq.com/ipaddress></script> <script type=text/javascript> var hehe1=IPData[2] var hehe2=IPData[3] alert(hehe1); alert(hehe2); document.write(IPData.join(' ')); </script> 如何用A

ASP 获取腾讯IP地址的代码

提问: 复制代码 代码如下: <script type=text/javascript src=http://fw.qq.com/ipaddress></script> <script type=text/javascript> var hehe1=IPData[2] var hehe2=IPData[3] alert(hehe1); alert(hehe2); document.write(IPData.join(' ')); </script> 如何用A

ASP获取远程文件大小信息(通过header头信息)

文件大小|远程文件|header ASP获取远程文件的通过header头信息,并返回远程文件大小信息,远程文件可以是网页或RAR,EXE任何格式的文件. 以下的代码是由阿里西西alixixi.com提供的最简化的写法. 以下是引用片段:<% 'ASP获取远程文件大小方法1 set xml = Server.CreateObject("MSXML2.XMLHTTP") xml.open "GET","http://www.alixixi.com/dow

用Asp获取Dll加密新闻内容

以下是代码:<%on error resume next  Dim objXMLHTTP, xml  Set xml = Server.CreateObject("Microsoft.XMLHTTP")   xml.Open "GET", "http://chanye.finance.sina.com.cn/yj/2005-01-05/236914.shtml", False  xml.Send  tmpstr= xml.responseT