asp.net DZ论坛中根据IP地址取得所在地的代码
2024-07-10 12:39:40
供稿:网友
使用方法: IpSearch.GetAddressWithIP("202.96.128.167")
CS类代码
代码如下:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
//引入的命名空间
using System.IO;
/// <summary>
/// 判断IP归属地类
/// </summary>
public class IpSearch
{
private static object lockHelper = new object();
static PHCZIP pcz = new PHCZIP();
static string filePath = "";
static bool fileIsExsit = true;
static IpSearch()
{
filePath = HttpContext.Current.Server.MapPath("~/ipdata.config");
pcz.SetDbFilePath(filePath);
}
/// <summary>
/// 返回IP查找结果
/// </summary>
/// <param name="IPValue">要查找的IP地址</param>
/// <returns></returns>
public static string GetAddressWithIP(string IPValue)
{
lock (lockHelper)
{
string result = pcz.GetAddressWithIP(IPValue.Trim());
if (fileIsExsit)
{
if (result.IndexOf("IANA") >= 0)
{
return "";
}
else
{
return result;
}
}
else
{
return null;
}
}
}
/// <summary>
/// 辅助类,用于保存IP索引信息
/// </summary>
///
public class CZ_INDEX_INFO
{
public UInt32 IpSet;
public UInt32 IpEnd;
public UInt32 Offset;
public CZ_INDEX_INFO()
{
IpSet = 0;
IpEnd = 0;
Offset = 0;
}
}
//读取纯真IP数据库类
public class PHCZIP
{
protected bool bFilePathInitialized;
protected string FilePath;
protected FileStream FileStrm;
protected UInt32 Index_Set;
protected UInt32 Index_End;
protected UInt32 Index_Count;
protected UInt32 Search_Index_Set;
protected UInt32 Search_Index_End;
protected CZ_INDEX_INFO Search_Set;
protected CZ_INDEX_INFO Search_Mid;
protected CZ_INDEX_INFO Search_End;
public PHCZIP()
{
bFilePathInitialized = false;
}
public PHCZIP(string dbFilePath)
{
bFilePathInitialized = false;
SetDbFilePath(dbFilePath);
}
//使用二分法查找索引区,初始化查找区间
public void Initialize()
{
Search_Index_Set = 0;
Search_Index_End = Index_Count - 1;
}
//关闭文件
public void Dispose()
{
if (bFilePathInitialized)
{
bFilePathInitialized = false;
FileStrm.Close();
//FileStrm.Dispose();
}
}
public bool SetDbFilePath(string dbFilePath)
{
if (dbFilePath == "")
{
return false;
}
try
{
FileStrm = new FileStream(dbFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch
{
return false;
}
//检查文件长度
if (FileStrm.Length < 8)
{
FileStrm.Close();