/// <summary> /// 读取目标IP的信息 /// </summary> /// <param name="fs"></param> /// <param name="reader"></param> /// <param name="offset"></param> /// <param name="ipToLoc"></param> /// <param name="ipBytes"></param> /// <returns></returns> private IPLocation GetIPInfo(FileStream fs, BinaryReader reader, long offset, IPAddress ipToLoc, byte[] ipBytes) { fs.Position = offset; //确认目标IP在记录的IP范围内 var endIP = reader.ReadBytes(4); var endIpVal = BitConverter.ToUInt32(endIP, 0); var ipVal = BitConverter.ToUInt32(ipBytes, 0); if (endIpVal < ipVal) { return(null); } string country; string zone; //读取重定向模式字节 var pattern = reader.ReadByte(); if (pattern == RedirectMode.Mode_1) { var countryOffsetBytes = reader.ReadBytes(IPFormat.RecOffsetLength); var countryOffset = IPFormat.ToUint(countryOffsetBytes); if (countryOffset == 0) { return(GetUnknownLocation(ipToLoc)); } fs.Position = countryOffset; if (fs.ReadByte() == RedirectMode.Mode_2) { return(ReadMode2Record(fs, reader, ipToLoc)); } fs.Position--; country = ReadString(reader); zone = ReadZone(fs, reader, Convert.ToUInt32(fs.Position)); } else if (pattern == RedirectMode.Mode_2) { return(ReadMode2Record(fs, reader, ipToLoc)); } else { fs.Position--; country = ReadString(reader); zone = ReadZone(fs, reader, Convert.ToUInt32(fs.Position)); } return(new IPLocation(ipToLoc, country, zone)); }
/// <summary> /// 按模式2读取记录 /// </summary> /// <param name="fs"></param> /// <param name="reader"></param> /// <param name="ip"></param> /// <returns></returns> private IPLocation ReadMode2Record(FileStream fs, BinaryReader reader, IPAddress ip) { var countryOffset = IPFormat.ToUint(reader.ReadBytes(IPFormat.RecOffsetLength)); var curOffset = Convert.ToUInt32(fs.Position); if (countryOffset == 0) { return(GetUnknownLocation(ip)); } fs.Position = countryOffset; var country = ReadString(reader); var zone = ReadZone(fs, reader, curOffset); return(new IPLocation(ip, country, zone)); }
/// <summary> /// 读取区域信息 /// </summary> /// <param name="fs"></param> /// <param name="reader"></param> /// <param name="offset"></param> /// <returns></returns> private string ReadZone(FileStream fs, BinaryReader reader, uint offset) { fs.Position = offset; var b = reader.ReadByte(); if (b == RedirectMode.Mode_1 || b == RedirectMode.Mode_2) { var zoneOffset = IPFormat.ToUint(reader.ReadBytes(3)); if (zoneOffset == 0) { return(IPFormat.UnknownZone); } return(ReadZone(fs, reader, zoneOffset)); } fs.Position--; return(ReadString(reader)); }