加入收藏 | 设为首页 | 会员中心 | 我要投稿 武汉站长网 (https://www.027zz.cn/)- 云连接、智能边缘云、数据快递、云手机、云日志!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

c#实现根据网络IP显示地理位置功能实例

发布时间:2023-06-08 15:30:25 所属栏目:语言 来源:转载
导读:   用户信息表,是大多数系统都有的。我们也知道,通常都会有类似 注册IP 和 最后登录IP 这两个的字段,来存储用户注册时候的IP地址和最后登录的IP的地址。



  获取这样的地址,在
  用户信息表,是大多数系统都有的。我们也知道,通常都会有类似 注册IP 和 最后登录IP 这两个的字段,来存储用户注册时候的IP地址和最后登录的IP的地址。
 
  获取这样的地址,在后台显示 xxx.xxx.xxx.xxx 的地址段,让人看到很不自然,根本就不知道具体地理位置。
 
  现在我们就简单的实现一下这个功能。
 
  用到了读取纯真IP数据库的公用组件QQWry.NET 这个组件,作者阿不。(谢谢他的共享)
 
  还要去下载最新的纯真IP地址库,下载获得QQWry.dat
 
  最后请出Js中的小靓妞,jquery-1.3.1.js
 
  新建Web项目AjaxIP,将QQWry.dat添加到App_Data下。
 
  然后添加QQWry.NET的组件类,如下:
 
  代码如下:
 
  Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 using System;
 
  using System.Collections.Generic;
 
  using System.Text;
 
  using System.IO;
 
  using System.Text.RegularExpressions;
 
  using System.Net;
 
  using System.Net.Sockets;
 
  namespace AjaxIP
 
  {
 
  public class IPLocation
 
  {
 
  public string IP { get; set; }
 
  public string Country { get; set; }
 
  public string Local { get; set; }
 
  }
 
  public class QQWryLocator
 
  {
 
  static Encoding encoding = Encoding.GetEncoding("GB2312");
 
  private byte[] data;
 
  int firstStartIpOffset;
 
  int lastStartIpOffset;
 
  int ipCount;
 
  public int 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);
 
  }
 
  firstStartIpOffset = (int)data[0] + (((int)data[1]) << 8) + (((int)data[2]) << 16) + (((int)data[3]) << 24);
 
  lastStartIpOffset = (int)data[4] + (((int)data[5]) << 8) + (((int)data[6]) << 16) + (((int)data[7]) << 24);
 
  ipCount = (lastStartIpOffset - firstStartIpOffset) / 7 + 1;
 
  if (ipCount <= 1)
 
  {
 
  throw new ArgumentException("ip FileDataError");
 
  }
 
  }
 
  public static uint IpToInt(string ip)
 
  {
 
  //string[] strArray = ip.Split('.');
 
  //return (uint.Parse(strArray[0]) << 24) + (uint.Parse(strArray[1]) << 16) + (uint.Parse(strArray[2]) << 8) + uint.Parse(strArray[0]);
 
  //return (uint)IPAddress.HostToNetworkOrder((int)(IPAddress.Parse(ip).Address));
 
  byte[] bytes = IPAddress.Parse(ip).GetAddressBytes();
 
  return (uint)bytes[3] + (((uint)bytes[2]) << 8) + (((uint)bytes[1]) << 16) + (((uint)bytes[0]) << 24);
 
  }
 
  public static string IntToIP(uint ip_Int)
 
  {
 
  return new IPAddress(ip_Int).ToString();
 
  }
 
  public IPLocation Query(string ip)
 
  {
 
  IPAddress address = IPAddress.Parse(ip);
 
  if (address.AddressFamily != AddressFamily.InterNetwork)
 
  {
 
  throw new ArgumentException("不支持非IPV4的地址");
 
  }
 
  if (IPAddress.IsLoopback(address))
 
  {
 
  return new IPLocation() { IP = ip, Country = "本机内部环回地址", Local = string.Empty };
 

(编辑:武汉站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章