第一步:在根目录添加新项(类),新建一个类文件,把以下文件粘贴到该类文件下:

 
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Diagnostics;
 
 
    public class RedirectMode
    {
        public static readonly int Mode_1 = 1;
        public static readonly int Mode_2 = 2;
    }
 
    public class IPFormat
    {
        public static readonly int HeaderLength = 8;
        public static readonly int IndexRecLength = 7;
        public static readonly int IndexOffset = 3;
        public static readonly int RecOffsetLength = 3;
 
        public static readonly string UnknownCountry = "未知的国家";
        public static readonly string UnknownZone = "未知的地区";
 
        public static uint ToUint(byte[] val)
        {
            if (val.Length > 4) throw new ArgumentException();
            if (val.Length < 4)
            {
                byte[] copyBytes = new byte[4];
                Array.Copy(val, 0, copyBytes, 0, val.Length);
                return BitConverter.ToUInt32(copyBytes, 0);
            }
            else
            {
                return BitConverter.ToUInt32(val, 0);
            }
        }
    }
 
    public class IPLocation
    {
        private IPAddress m_ip;
        private string m_country;
        private string m_loc;
 
        public IPLocation(IPAddress ip, string country, string loc)
        {
            m_ip = ip;
            m_country = country;
            m_loc = loc;
        }
 
        public IPAddress IP
        {
            get { return m_ip; }
        }
 
        public string Country
        {
            get { return m_country; }
        }
 
        public string Zone
        {
            get { return m_loc; }
        }
    }
 
    /// <summary> 
    /// This class used to control ip seek 
    /// </summary> 
    public class IPSeeker
    {
        private string m_libPath;
        private uint m_indexStart;
        private uint m_indexEnd;
        public IPSeeker(string libPath)
        {
            m_libPath = libPath;
            //Locate the index block 
            using (FileStream fs = new FileStream(m_libPath, FileMode.Open, FileAccess.Read))
            {
 
                BinaryReader reader = new BinaryReader(fs);
                Byte[] header = reader.ReadBytes(IPFormat.HeaderLength);
                m_indexStart = BitConverter.ToUInt32(header, 0);
                m_indexEnd = BitConverter.ToUInt32(header, 4);
 
            }
        }
 
        /// <summary> 
        /// 输入IP地址,获取IP所在的地区信息 
        /// </summary> 
        /// <param name="ip">待查询的IP地址</param> 
        /// <returns></returns> 
        public IPLocation GetLocation(IPAddress ip)
        {
            using (FileStream fs = new FileStream(m_libPath, FileMode.Open, FileAccess.Read))
            {
                BinaryReader reader = new BinaryReader(fs);
                //Because it is network order(BigEndian), so we need to transform it into LittleEndian 
                Byte[] givenIpBytes = BitConverter.GetBytes(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(ip.GetAddressBytes(), 0)));
                uint offset = FindStartPos(fs, reader, m_indexStart, m_indexEnd, givenIpBytes);
                return GetIPInfo(fs, reader, offset, ip, givenIpBytes);
            }
        }
 
        #region private method
        private uint FindStartPos(FileStream fs, BinaryReader reader, uint m_indexStart, uint m_indexEnd, byte[] givenIp)
        {
            uint givenVal = BitConverter.ToUInt32(givenIp, 0);
            fs.Position = m_indexStart;
 
            while (fs.Position <= m_indexEnd)
            {
                Byte[] bytes = reader.ReadBytes(IPFormat.IndexRecLength);
                uint curVal = BitConverter.ToUInt32(bytes, 0);
                if (curVal > givenVal)
                {
                    fs.Position = fs.Position - 2 * IPFormat.IndexRecLength;
                    bytes = reader.ReadBytes(IPFormat.IndexRecLength);
                    byte[] offsetByte = new byte[4];
                    Array.Copy(bytes, 4, offsetByte, 0, 3);
                    return BitConverter.ToUInt32(offsetByte, 0);
                }
            }
            return 0;
        }
 
        private IPLocation GetIPInfo(FileStream fs, BinaryReader reader, long offset, IPAddress ipToLoc, Byte[] ipBytes)
        {
            fs.Position = offset;
            //To confirm that the given ip is within the range of record IP range 
            byte[] endIP = reader.ReadBytes(4);
            uint endIpVal = BitConverter.ToUInt32(endIP, 0);
            uint ipVal = BitConverter.ToUInt32(ipBytes, 0);
            if (endIpVal < ipVal) return null;
 
            string country;
            string zone;
            //Read the Redirection pattern byte 
            Byte pattern = reader.ReadByte();
            if (pattern == RedirectMode.Mode_1)
            {
                Byte[] countryOffsetBytes = reader.ReadBytes(IPFormat.RecOffsetLength);
                uint countryOffset = IPFormat.ToUint(countryOffsetBytes);
 
                if (countryOffset == 0) return GetUnknownLocation(ipToLoc);
 
                fs.Position = countryOffset;
                if (fs.ReadByte() == RedirectMode.Mode_2)
                {
                    return ReadMode2Record(fs, reader, ipToLoc);
                }
                else
                {
                    fs.Position--;
                    country = ReadString(reader);
                    zone = ReadZone(fs, reader, Convert.ToUInt32(fs.Position));
                }
            }
            else if (pattern == RedirectMode.Mode_2)
            {
                return ReadMode2Record(fs, reader, ipToLoc);
            }
            else
            {
                fs.Position--;
                country = ReadString(reader);
                zone = ReadZone(fs, reader, Convert.ToUInt32(fs.Position));
            }
            return new IPLocation(ipToLoc, country, zone);
 
        }
 
        //When it is in Mode 2 
        private IPLocation ReadMode2Record(FileStream fs, BinaryReader reader, IPAddress ip)
        {
            uint countryOffset = IPFormat.ToUint(reader.ReadBytes(IPFormat.RecOffsetLength));
            uint curOffset = Convert.ToUInt32(fs.Position);
            if (countryOffset == 0) return GetUnknownLocation(ip);
            fs.Position = countryOffset;
            string country = ReadString(reader);
            string zone = ReadZone(fs, reader, curOffset);
            return new IPLocation(ip, country, zone);
        }
 
        //return a Unknown Location 
        private IPLocation GetUnknownLocation(IPAddress ip)
        {
            string country = IPFormat.UnknownCountry;
            string zone = IPFormat.UnknownZone;
            return new IPLocation(ip, country, zone);
        }
        //Retrieve the zone info 
        private string ReadZone(FileStream fs, BinaryReader reader, uint offset)
        {
            fs.Position = offset;
            byte b = reader.ReadByte();
            if (b == RedirectMode.Mode_1 || b == RedirectMode.Mode_2)
            {
                uint zoneOffset = IPFormat.ToUint(reader.ReadBytes(3));
                if (zoneOffset == 0) return IPFormat.UnknownZone;
                return ReadZone(fs, reader, zoneOffset);
            }
            else
            {
                fs.Position--;
                return ReadString(reader);
            }
        }
 
        private string ReadString(BinaryReader reader)
        {
            List<byte> stringLst = new List<byte>();
            byte byteRead = 0;
            while ((byteRead = reader.ReadByte()) != 0)
            {
                stringLst.Add(byteRead);
            }
            return Encoding.GetEncoding("gb2312").GetString(stringLst.ToArray());
        }
        #endregion
    }
 

第二步:编写测试文件,Default.aspx.cs中粘贴覆盖以下代码,其中鹅黄色为测试代码;然后F5测试,弹窗说明成功;

 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
 
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string ip = Request.ServerVariables.Get("REMOTE_ADDR");//自动获取用户IP 
        //string ip = TextBox1.Text.Trim(); 
        if (ip == string.Empty) return;
        IPSeeker seeker = new IPSeeker(Server.MapPath(@"data/QQWry.Dat"));//纯真IP地址库存放目录!!
        System.Net.IPAddress ipaddr = System.Net.IPAddress.Parse(ip);
        IPLocation loc = seeker.GetLocation(ipaddr);
        if (loc == null)
        {
            Response.Write("<script>alert('指定的IP地址无效!')</script>");
        }
        Response.Write("<script>alert('地址:" + loc.Country + loc.Zone + "')</script>");
    }
}
 

C# .net 如何根据访问者IP获取所在地区的更多相关文章

  1. C# 解析百度天气数据,Rss解析百度新闻以及根据IP获取所在城市

    百度天气 接口地址:http://api.map.baidu.com/telematics/v3/weather?location=上海&output=json&ak=hXWAgbsC ...

  2. 根据IP获取所在的国家城市

    根据IP获取所在的国家城市 新浪的IP地址查询接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js 新浪多地域测试方法:htt ...

  3. ip获取所在城市名称等信息接口,及函数

    函数: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 ...

  4. 获取访问者ip及其所在城市

    原本使用新浪Api,然后发现不行了,以下小编重新查找了几个,个人推荐太平洋的接口 1.首先获取真实ip $ip = $_SERVER['REMOTE_ADDR']; 2.要知道的Api接口 几个接口$ ...

  5. 通过GeoIP2分析访问者IP获取地理位置信息

    原文链接:http://blog.csdn.net/johnnycode/article/details/42028841 MaxMind GeoIP2 服务能识别互联网用户的地点位置与其他特征,应用 ...

  6. 通过IP获取所在城市

    <script type="text/javascript"> var map = new BMap.Map("allmap"); var poin ...

  7. php根据IP获取所在省份-淘宝api接口

    这里用的file_put_contents,你也可以用别的,直接怼代码: //拼接传递的参数$ip = '175.12.53.12' $opts = array( 'http'=>array( ...

  8. php根据IP获取所在省份-百度api接口

    这里用的file_put_contents,你也可以用别的,直接怼代码: //拼接传递的参数 $getData = array( 'query' => '127.0.0.1', 'resourc ...

  9. 读取全球ip获取用户地区

    这个 首先说明下.ip库是qq纯真ip库 dat文件类型 public static string QQipPath = AppDomain.CurrentDomain.BaseDirectory + ...

随机推荐

  1. POJ 3468 A Simple Problem with Integers(详细题解) 线段树

    这是个线段树题目,做之前必须要有些线段树基础才行不然你是很难理解的. 此题的难点就是在于你加的数要怎么加,加入你一直加到叶子节点的话,复杂度势必会很高的 具体思路 在增加时,如果要加的区间正好覆盖一个 ...

  2. QTP中FSO的使用

    序 FSO即文件系统对象(File System Object),在测试工作中有广泛的应有,它可以帮助我们自动生成测试目录,写日志,测试报告等.FSO有对象有很多属性和方法,今天只介绍几个常用的. 创 ...

  3. 在kafka上对topic新增partition

    对topic增加partition 参考官网site:http://kafka.apache.org/documentation.html#basic_ops_modify_topic 通过kafka ...

  4. ubuntu12编译openwrt

    搭建编译环境 Ubuntu x64 12.04下的命令: sudo apt-get install subversion sudo apt-get install git sudo apt-get i ...

  5. Python字符串连接的5种方法

    总结了一下Python字符串连接的5种方法: 加号 第一种,有编程经验的人,估计都知道很多语言里面是用加号连接两个字符串,Python里面也是如此直接用 "+" 来连接两个字符串: ...

  6. 快速查询本机IP 分类: windows常用小技巧 2014-04-15 09:28 138人阅读 评论(0) 收藏

    第一步: 点击windows建(屏幕左下方),在搜索程序和文件文本框内输入:cmd 第二步:      点击Enter建进入. 第三步: 输入:ipconfig即可. 版权声明:本文为博主原创文章,未 ...

  7. IOS中内存管理机制浅解

    我们知道在程序运行过程中要创建大量的对象,和其他高级语言类似,在ObjC中对象时存储在堆中的,系统并不会自动释放堆中的内存(注意基本类型是 由系统自己管理的,放在栈上).如果一个对象创建并使用后没有得 ...

  8. Shiro Quartz之Junit測试Session管理

    Shiro的quartz主要API上提供了org.apache.shiro.session.mgt.quartz下session管理的两个类:QuartzSessionValidationJob和Qu ...

  9. android EditText中的inputType

    android 1.5以后添加了软件虚拟键盘的功能,所以在输入提示中将会有对应的软键盘模式 android中inputType属性在EditText输入值时启动的虚拟键盘的风格有着重要的作用.这也大大 ...

  10. RJ45口线序的理解

    RJ45线序就是TX_P / TX_N / RX_P / RX_N 四根线,分别用到的是1,2,3,6 因为TX要匹配RX,所以 线1 变成 另一端的 线3, 线2 变成 另一端的 线6 反过来也一样