Ejemplo n.º 1
0
        public IPResponse FindByIp(string searchAddress)
        {
            IPAddress ipAddress;

            if (!IPAddress.TryParse(searchAddress, out ipAddress))
            {
                return(null);
            }
            var  ipBytes = ipAddress.GetAddressBytes();
            uint ip      = (uint)ipBytes[3];

            ip += (uint)ipBytes[2] << 8;
            ip += (uint)ipBytes[1] << 16;
            ip += (uint)ipBytes[0] << 24;

            int startIndex  = 0;
            int finishIndex = GeobaseStorage.IpData.Length;

            while (true)
            {
                int averageIndex = startIndex + (finishIndex - startIndex) / 2;
                if (averageIndex == startIndex || averageIndex == finishIndex)
                {
                    return(new IPResponse());
                }
                if (ip >= GeobaseStorage.IpData[averageIndex].ip_from && ip <= GeobaseStorage.IpData[averageIndex].ip_to)
                {
                    var location = GeobaseStorage.LocationData[GeobaseStorage.IpData[averageIndex].location_index];
                    return(ResponseCreator.CreateIPResponse(GeobaseStorage.IpData[averageIndex], location));
                }
                if (ip < GeobaseStorage.IpData[averageIndex].ip_to)
                {
                    finishIndex = averageIndex;
                }
                else
                {
                    startIndex = averageIndex;
                }
            }
        }