Programming languages: C #
Category: (Network applications, practical algorithms)
Main function: Query an IP of all IP segments.
Key: The converted numbers from the byte array to the ULONG and the ipaddress.address return values are not the same. Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;
Namespace Iputility
{
Class Program
{
static void Main (string[] args)
{
Iprangemanage IRM = new Iprangemanage ();
Irm. ADD (new IPRange ("Shijiazhuang", "219.148.24.0", "219.148.63.255"));
Irm. ADD (new IPRange ("Shijiazhuang", "222.222.0.0", "222.222.63.255"));
Irm. ADD (new IPRange ("Tangshan", "219.148.64.0", "219.148.79.255"));
Irm. ADD (new IPRange ("Baoding", "219.148.20.0", "219.148.23.255"));
Console.WriteLine (IRM. Search ("219.148.56.3"). Name);
Console.ReadLine ();
}
}
public class IPRange
{
private string _name = String. Empty;
Private ulong _beginip = 0;
Private ulong _endip = Int32.MaxValue;
/**////<summary>
IP segment Name
</summary>
public string Name
{
get {return _name;}
set {_name = value;}
}
/**////<summary>
? Start IP
</summary>
Public ULONG Beginip
{
get {return _beginip;}
set {_beginip = value;}
}
/**////<summary>
? Bundle IP
</summary>
Public ULONG EndIP
{
get {return _endip;}
set {_endip = value;}
}
/**////<summary>
Fan of this IP segment?
</summary>
Public ULONG Range
{
Get
{
return endip-beginip;
}
}
public IPRange (string name, String ipbegin, String ipend)
{
This. name = name;
This. Beginip = IP2A (Ipbegin);
This. EndIP = IP2A (ipend);
}
public static ULONG IP2A (string IP)
{
byte[] bytes = Ipaddress.parse (IP). Getaddressbytes ();
ULONG ret = 0;
foreach (Byte b in bytes)
{
RET <<= 8;
RET |= B;
}
return ret;
}
public static int Compare (IPRange x, iprange y)
{
if (X.range = = Y.range)
return 0;
else if (X.range > Y.range)
return 1;
else return-1;
}
}
public class Iprangemanage
{
Public Iprangemanage ()
{ }
Private list< iprange> _iprangelist = new list< iprange> ();
private bool _needsort = true;
public void Add (iprange iprange)
{
_iprangelist.add (IPRange);
_needsort = true;
}
private void Sort ()
{
if (_needsort)
{
_iprangelist.sort (New comparison<iprange> (Iprange.compare));
}
}
public IPRange Search (string ipstring)
{
ULONG IP = IPRANGE.IP2A (ipstring);
This. Sort ();
foreach (IPRange ir in _iprangelist)
{
if (IR. Beginip <= IP && ir. EndIP >= IP)
{
return IR;
}
}
return null;
}
}
}