编程语言C#
类 别(网络应用实用算法)
主要功能查询一个IP所有的IP段 关键:从Byte数组到ulong的转换出来的数字和 IPAddressAddress 返回值的是不一样的
using System;
using SystemCollectionsGeneric;
using SystemText;
using SystemNet;
namespace IPUtility
{
class Program
{
static void Main(string[] args)
{
IPRangeManage irm = new IPRangeManage();
irmAdd(new IPRange(石家庄 ));
irmAdd(new IPRange(石家庄 ));
irmAdd(new IPRange(唐山 ));
irmAdd(new IPRange(保定 ));
ConsoleWriteLine(irmSearch()Name);
ConsoleReadLine();
}
}
public class IPRange
{
private string _Name = stringEmpty;
private ulong _BeginIP = ;
private ulong _EndIP = IntMaxValue;
/**//// <summary>
/// IP段名称
/// </summary>
public string Name
{
get { return _Name; }
set { _Name = value; }
}
/**//// <summary>
/// ?始IP
/// </summary>
public ulong BeginIP
{
get { return _BeginIP; }
set { _BeginIP = value; }
}
/**//// <summary>
/// ?束IP
/// </summary>
public ulong EndIP
{
get { return _EndIP; }
set { _EndIP = value; }
}
/**//// <summary>
/// 此IP段的范?
/// </summary>
public ulong Range
{
get
{
return EndIP BeginIP;
}
}
public IPRange(string name string ipBegin string ipEnd)
{
thisName = name;
thisBeginIP = IPA(ipBegin);
thisEndIP = IPA(ipEnd);
}
public static ulong IPA(string ip)
{
byte[] bytes = IPAddressParse(ip)GetAddressBytes();
ulong ret = ;
foreach (byte b in bytes)
{
ret <<= ;
ret |= b;
}
return ret;
}
public static int Compare(IPRange x IPRange y)
{
if(xRange == yRange)
return ;
else if(xRange > yRange)
return ;
else return ;
}
}
public class IPRangeManage
{
public IPRangeManage()
{ }
private List< IPRange> _IPRangeList = new List< IPRange>();
private bool _NeedSort = true;
public void Add(IPRange ipRange)
{
_IPRangeListAdd(ipRange);
_NeedSort = true;
}
private void Sort()
{
if (_NeedSort)
{
_IPRangeListSort(new Comparison<IPRange>(IPRangeCompare));
}
}
public IPRange Search(string ipString)
{
ulong ip = IPRangeIPA(ipString);
thisSort();
foreach (IPRange ir in _IPRangeList)
{
if (irBeginIP <= ip && irEndIP >= ip)
{
return ir;
}
}
return null;
}
}
}