c#實現根據網絡IP顯示地理位置功能示例
2024-09-07 17:05:31
供稿:網友
用戶信息表,是大多數系統都有的。我們也知道,通常都會有類似 注冊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 };