Public class IpHelper
{
// Core method: IP search
/// <Summary>
/// Find the region where the IP is located and make sure that the web. config contains the IPData or BackIpData configuration section.
/// </Summary>
/// <Param name = "ips"> IP </param>
/// <Returns> </returns>
Public static IpLocation GetIpLocation (string ips)
{
String fn = HttpContext. Current. Server. MapPath (ConfigurationManager. configurettings ["IPData"]);
String backData = HttpContext. Current. Server. MapPath (ConfigurationManager. receivettings ["BackIpData"]);
If (! File. Exists (fn ))
{
If (! File. Exists (backData ))
{
Throw new Exception ("the file does not exist ");
}
Fn = backData;
}
FileStream fs = new FileStream (fn, FileMode. Open, FileAccess. Read, FileShare. Read );
BinaryReader fp = new BinaryReader (fs );
// Read the file header to obtain the offset of the first and last records
Int fo = fp. ReadInt32 ();
Int lo = fp. ReadInt32 ();
// IP Value
Uint ipv = IpStringToInt (ips );
// Get the Offset Value of the IP index record
Int rcOffset = getIndexOffset (fs, fp, fo, lo, ipv );
Fs. Seek (rcOffset, System. IO. SeekOrigin. Begin );
IpLocation ipl;
If (rcOffset> = 0)
{
Fs. Seek (rcOffset, System. IO. SeekOrigin. Begin );
// Read the IP value starting
Ipl. IpStart = fp. ReadUInt32 ();
// Transfer to record body
Fs. Seek (ReadInt24 (fp), System. IO. SeekOrigin. Begin );
// Read the end IP address value
Ipl. IpEnd = fp. ReadUInt32 ();
Ipl. Country = GetString (fs, fp );
Ipl. City = GetString (fs, fp );
}
Else
{
// Not found
Ipl. IpStart = 0;
Ipl. IpEnd = 0;
Ipl. Country = "unknown Country ";
Ipl. City = "unknown address ";
}
Fp. Close ();
Fs. Close ();
Return ipl;
}
// Function: uses the "bipartite" method to search for the index area and locate the IP index record location.
Private static int getIndexOffset (FileStream fs, BinaryReader fp, int _ fo, int _ lo, uint ipv)
{
Int fo = _ fo, lo = _ lo;
Int mo; // The intermediate offset.
Uint mv; // median value
Uint fv, lv; // Boundary Value
Uint llv; // The Last boundary value.
Fs. Seek (fo, System. IO. SeekOrigin. Begin );
Fv = fp. ReadUInt32 ();
Fs. Seek (lo, System. IO. SeekOrigin. Begin );
Lv = fp. ReadUInt32 ();
// Use it temporarily, and the offset of the last record body
Mo = ReadInt24 (fp );
Fs. Seek (mo, System. IO. SeekOrigin. Begin );
Llv = fp. ReadUInt32 ();
// Border detection processing
If (ipv <fv)
Return-1;
Else if (ipv> llv)
Return-1;
// Use the "bipartite" Method to Determine the record offset
& Nb