2025-10-21 13:38:23 +08:00
using IP2Region.Net.XDB ;
using System ;
using System.IO ;
using RIZO.Infrastructure.IPTools.Model ;
namespace RIZO.Infrastructure.IPTools
{
public class IpTool
{
private static readonly string DbPath = Path . Combine ( AppDomain . CurrentDomain . BaseDirectory , "ip2region.xdb" ) ;
private static readonly Searcher Searcher ;
static IpTool ( )
{
if ( ! File . Exists ( DbPath ) )
{
throw new Exception ( $"IP initialize failed. Can not find database file from {DbPath}. Please download the file to your application root directory, then set it can be copied to the output directory. Url: https://gitee.com/lionsoul/ip2region/blob/master/data/ip2region.xdb" ) ;
}
Searcher = new Searcher ( CachePolicy . File , DbPath ) ;
}
public static string GetRegion ( string ip )
{
if ( string . IsNullOrEmpty ( ip ) )
{
throw new ArgumentException ( "IP为空" , nameof ( ip ) ) ;
}
try
{
var region = Searcher . Search ( ip ) ;
return region ;
}
catch ( Exception ex )
{
Console . WriteLine ( ex . Message ) ;
throw new Exception ( $"搜索IP异常IP={ip}" , ex ) ;
}
}
public static IpInfo Search ( string ip )
{
try
{
var region = GetRegion ( ip ) ;
2026-01-10 09:40:54 +08:00
// 新增: 校验region是否为null或空字符串
if ( string . IsNullOrEmpty ( region ) )
{
// 处理空值情况( 例如返回默认IpInfo、抛出自定义异常等)
return new IpInfo { Country = "未知" , Province = "未知" , City = "未知" , NetworkOperator = "未知" , IpAddress = ip } ;
}
2025-10-21 13:38:23 +08:00
var array = region . Split ( "|" ) ;
var info = new IpInfo ( )
{
Country = array [ 0 ] ,
Province = array [ 2 ] ,
City = array [ 3 ] ,
NetworkOperator = array [ 4 ] ,
IpAddress = ip
} ;
return info ;
}
catch ( Exception e )
{
throw new Exception ( "Error converting ip address information to ipinfo object" , e ) ;
}
}
}
}