How does the binary DAT from Maxmind work?

主宰稳场 提交于 2019-12-03 16:24:02

It's just a proprietary binary format, heavily optimized for IP address querying. It doesn't have any copy protection.

If you really want to reverse-engineer the format, take a look at the C# or Java API.

I don't know if this helps but here it's a sample code in PHP for the GeoLite Country DB:

const COUNTRY_BEGIN = 16776960;
const COUNTRY_EDITION = 106;
const STANDARD_RECORD_LENGTH = 3;

public function Seek_Country($ip)
{
    $result = false;

    $databases = glob('./application/repository/GeoIP/GeoIP_*.dat');

    if (array_key_exists(0, $databases))
    {
        rsort($databases);

        if (!$handle = fopen($databases[0], 'rb'))
        {
            return $result;
        }

        $offset = 0;

        flock($handle, LOCK_SH);

        for ($depth = 31; $depth >= 0; --$depth)
        {
            fseek($handle, 2 * self::STANDARD_RECORD_LENGTH * $offset, SEEK_SET);

            $buffer = fread($handle, 2 * self::STANDARD_RECORD_LENGTH);

            $x = array(0, 0);

            for ($i = 0; $i < 2; ++$i)
            {
                for ($j = 0; $j < self::STANDARD_RECORD_LENGTH; ++$j)
                {
                    $x[$i] += ord($buffer[self::STANDARD_RECORD_LENGTH * $i + $j]) << ($j * 8);
                }
            }

            if ($ip & (1 << $depth))
            {
                if ($x[1] >= self::COUNTRY_BEGIN)
                {
                    $result = $x[1];

                    break;
                }

                $offset = $x[1];
            }

            else
            {
                if ($x[0] >= self::COUNTRY_BEGIN)
                {
                    $result = $x[0];

                    break;
                }

                $offset = $x[0];
            }
        }

        flock($handle, LOCK_UN);
        fclose($handle);
    }

    return $result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!