using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using WingServerCommon.Utilities;
namespace WingServerCommon.Interfaces.Cache
{
///
/// IP 管理接口
///
public interface IIPManager : IBaseCacheManager
{
///
/// 根据IP获取内存中对应IP段的详细信息
///
/// ip
/// IP段的详细信息
public CacheIPInfoDTO GetIPInfo(string ip);
///
/// 加载IP段文件
///
/// 文件路径
public void LoadData(string path);
}
///
/// IP 管理类
///
public class IPManager : CacheManager, IIPManager
{
private List _ipList = new List();
private StartRangeComparer startRangeComparer = new StartRangeComparer();
///
/// 根据IP获取内存中对应IP段的详细信息
///
///
///
public CacheIPInfoDTO GetIPInfo(string ip)
{
using (new Performance(5, "{0} GetIPInfo {1}", $"{this.GetType().Name}",$"{ip}"))
{
var longIP = IpToLong(ip);
var index = _ipList.BinarySearch(new CacheIPInfoDTO { LongStartIP = longIP }, startRangeComparer);
int candidateIndex = index >= 0 ? index : (~index) - 1;
if (candidateIndex < 0)
{
return null;
}
CacheIPInfoDTO candidate = _ipList[candidateIndex];
if (candidate.LongEndIP >= longIP)
{
return candidate;
}
else
{
return null;
};
}
}
///
/// 加载IP段文件
///
/// 文件路径
public void LoadData(string path)
{
List list = new List();
DirectoryInfo dirInfo = new DirectoryInfo(path);
if (dirInfo != null)
{
FileInfo[] fileInfos = dirInfo.GetFiles();
if (fileInfos != null && fileInfos.Length > 0)
{
foreach (var fileInfo in fileInfos)
{
using (FileStream fs = new FileStream(fileInfo.FullName, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8))
{
var json = sr.ReadToEnd();
if (!string.IsNullOrEmpty(json))
{
var contentList = Newtonsoft.Json.JsonConvert.DeserializeObject>(json);
if (contentList != null && contentList.Count > 0)
{
list.AddRange(contentList);
}
}
}
}
}
}
}
_ipList = list.OrderBy(v => v.LongStartIP).ToList();
}
///
/// ip to long
///
///
///
private long IpToLong(string ip)
{
byte[] byts = IPAddress.Parse(ip).GetAddressBytes();
Array.Reverse(byts); // 需要倒置一次字节序
long ipLong = BitConverter.ToUInt32(byts, 0);
return ipLong;
}
}
public class StartRangeComparer : IComparer
{
public int Compare(CacheIPInfoDTO first, CacheIPInfoDTO second)
{
return first.LongStartIP.CompareTo(second.LongStartIP);
}
}
///
/// IP 信息对象类
///
public class CacheIPInfoDTO : ICacheObject
{
///
/// 起始 long 类型IP
///
///
public long LongStartIP { get; set; }
///
/// 结束 long 类型IP
///
///
public long LongEndIP { get; set; }
///
///纬度
///
///
public double Lat { get; set; }
///
/// 经度
///
///
public double Lng { get; set; }
///
/// 国家
///
///
public string Country { get; set; }
///
///省
///
///
public string Province { get; set; }
///
///城市
///
///
public string City { get; set; }
///
///区县
///
///
public string Districts { get; set; }
///
///是否中国大陆境内或者境外
///
///
public bool IsChinaMainland { get; set; }
///
///
///
///
public string Code { get; set; }
}
}