萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 根據 IP 查詢地理位置:基於 qqwry.dat 純真數據庫的完整實現

離線 IP 地理位置查詢:解析 qqwry.dat 格式與 PHP 實現

純真 IP 數據庫 (qqwry.dat) 是國內廣泛使用的免費 IP 地址庫,體積小(~8MB)、更新頻繁、查詢極快。本文深度解析其二進制格式,並提供高性能 PHP 解析類(支援 IPv4、自動編碼轉換、內存映射優化)。

qqwry.dat 文件結構解析

  • 文件頭 (8 字節):前 4 字節 = 第一條記錄偏移量,後 4 字節 = 最後一條記錄偏移量(小端序)。
  • 索引區:每條 7 字節 = 4 字節起始 IP + 3 字節記錄偏移量指向數據區。
  • 數據區:變長記錄,包含結束 IP(4 字節)、國家/地區信息(兩種壓縮模式:直接字符串 或 偏移指針)。
  • 查找算法:二分查找索引區 → 定位數據區 → 解析國家/地區字符串(處理壓縮指針遞歸)。

高性能 PHP 解析類(支援緩存索引、GBK 轉 UTF-8)

<?php
/**
 * 純真 IP 數據庫解析器 (qqwry.dat)
 * 支援 IPv4、二分查找、壓縮指針遞歸解析、GBK/UTF-8 自動轉換
 */
class IpLocation
{
    private $fp;          // 文件指針
    private int $firstIp; // 首記錄偏移
    private int $lastIp;  // 末記錄偏移
    private int $totalIp; // 總記錄數
    private array $indexCache = []; // 可選:索引緩存到內存加速

    public function __construct(string $filename = 'qqwry.dat', bool $loadIndexToMemory = false)
    {
        $this->fp = @fopen($filename, 'rb');
        if (!$this->fp) {
            throw new \RuntimeException("無法打開 IP 數據庫文件: $filename");
        }
        $this->firstIp = $this->readLong();
        $this->lastIp  = $this->readLong();
        $this->totalIp = ($this->lastIp - $this->firstIp) / 7;

        if ($loadIndexToMemory) {
            $this->loadIndexCache();
        }
    }

    /** 將索引區完整讀入內存(約 7 * 總記錄數 字節,~5MB),大幅提升查詢速度 */
    private function loadIndexCache(): void
    {
        fseek($this->fp, $this->firstIp);
        $this->indexCache = [];
        for ($i = 0; $i < $this->totalIp; $i++) {
            $startIp = $this->readLong(); // 4 字節
            $offset  = $this->readLong3(); // 3 字節
            $this->indexCache[] = ['start' => $startIp, 'offset' => $offset];
        }
    }

    /** 讀取 4 字節無符號長整型 (小端序) */
    private function readLong(): int
    {
        $bytes = fread($this->fp, 4);
        return unpack('V', $bytes)[1];
    }

    /** 讀取 3 字節無符號長整型 (小端序,補齊 1 字節 0) */
    private function readLong3(): int
    {
        $bytes = fread($this->fp, 3) . "\x00";
        return unpack('V', $bytes)[1];
    }

    /** IP 字符串轉大端序 4 字節二進制 (用於比較) */
    private function packIp(string $ip): string
    {
        return pack('N', ip2long($ip) ?? -1); // 非法 IP 轉為 255.255.255.255
    }

    /** 讀取以 \0 結尾的字符串,並轉 UTF-8 */
    private function readString(string $prefix = ''): string
    {
        $str = $prefix;
        while (($char = fread($this->fp, 1)) !== false && $char !== "\x00") {
            $str .= $char;
        }
        // qqwry.dat 內部編碼為 GBK,轉為 UTF-8
        return mb_convert_encoding($str, 'UTF-8', 'GBK');
    }

    /** 解析區域信息(處理壓縮指針模式 0x01/0x02) */
    private function readArea(): string
    {
        $byte = fread($this->fp, 1);
        $flag = ord($byte);
        if ($flag === 0) return '';
        if ($flag === 1 || $flag === 2) {
            // 區域信息被重定向
            fseek($this->fp, $this->readLong3());
            return $this->readString();
        }
        // 直接字符串
        return $this->readString($byte);
    }

    /** 核心查詢方法 */
    public function getLocation(string $ip): ?array
    {
        if (!$this->fp) return null;

        $ip = gethostbyname($ip); // 域名解析
        $packedIp = $this->packIp($ip);

        // 二分查找
        $l = 0;
        $u = $this->totalIp - 1;
        $foundOffset = $this->lastIp; // 默認指向版本信息記錄

        if (!empty($this->indexCache)) {
            // 內存索引二分(極快)
            while ($l <= $u) {
                $i = ($l + $u) >> 1;
                $startIp = $this->indexCache[$i]['start'];
                if ($packedIp < pack('N', $startIp)) {
                    $u = $i - 1;
                } else {
                    // 讀取結束 IP
                    fseek($this->fp, $this->indexCache[$i]['offset']);
                    $endIp = $this->readLong();
                    if ($packedIp > pack('N', $endIp)) {
                        $l = $i + 1;
                    } else {
                        $foundOffset = $this->firstIp + $i * 7;
                        break;
                    }
                }
            }
        } else {
            // 文件索引二分(標準)
            while ($l <= $u) {
                $i = ($l + $u) >> 1;
                fseek($this->fp, $this->firstIp + $i * 7);
                $startIp = strrev(fread($this->fp, 4)); // 小端轉大端比較
                if ($packedIp < $startIp) {
                    $u = $i - 1;
                } else {
                    fseek($this->fp, $this->readLong3());
                    $endIp = strrev(fread($this->fp, 4));
                    if ($packedIp > $endIp) {
                        $l = $i + 1;
                    } else {
                        $foundOffset = $this->firstIp + $i * 7;
                        break;
                    }
                }
            }
        }

        // 解析找到的記錄
        fseek($this->fp, $foundOffset);
        $location = [
            'ip'      => $ip,
            'beginIp' => long2ip($this->readLong()),
            'endIp'   => '',
            'country' => '',
            'area'    => '',
        ];

        $dataOffset = $this->readLong3();
        fseek($this->fp, $dataOffset);
        $location['endIp'] = long2ip($this->readLong());

        $flag = ord(fread($this->fp, 1));
        switch ($flag) {
            case 1: // 國家和區域都重定向
                $countryOffset = $this->readLong3();
                fseek($this->fp, $countryOffset);
                $flag2 = ord(fread($this->fp, 1));
                if ($flag2 === 2) { // 國家又重定向
                    fseek($this->fp, $this->readLong3());
                    $location['country'] = $this->readString();
                    fseek($this->fp, $countryOffset + 4);
                } else {
                    $location['country'] = $this->readString($flag2 === 0 ? '' : chr($flag2));
                }
                $location['area'] = $this->readArea();
                break;
            case 2: // 國家重定向
                fseek($this->fp, $this->readLong3());
                $location['country'] = $this->readString();
                fseek($this->fp, $dataOffset + 8);
                $location['area'] = $this->readArea();
                break;
            default: // 直接字符串
                $location['country'] = $this->readString(chr($flag));
                $location['area'] = $this->readArea();
                break;
        }

        // 過濾純真數據庫特有標記
        if (str_contains($location['country'], 'CZ88.NET')) $location['country'] = '未知';
        if (str_contains($location['area'], 'CZ88.NET'))   $location['area'] = '';

        return $location;
    }

    public function __destruct()
    {
        if ($this->fp) fclose($this->fp);
    }
}

// ===== 使用示例 =====
$ipLocator = new IpLocation(__DIR__ . '/qqwry.dat', true); // true=載入索引到內存

$testIps = ['8.8.8.8', '114.114.114.114', '223.5.5.5', '192.168.1.1', 'www.baidu.com'];
foreach ($testIps as $ip) {
    $loc = $ipLocator->getLocation($ip);
    echo "$ip => {$loc['country']} {$loc['area']} ({$loc['beginIp']} - {$loc['endIp']})\n";
}
/*
輸出示例:
8.8.8.8 => 美國 加利福尼亞州聖克拉拉縣谷歌公司 (8.8.8.0 - 8.8.8.255)
114.114.114.114 => 江蘇省南京市 電信 (114.114.114.0 - 114.114.114.255)
192.168.1.1 => 內網IP (192.168.0.0 - 192.168.255.255)
*/
?>

性能優化關鍵點

  1. 索引緩存到內存:構造函數傳 true 將 7 字節×記錄數(約 5MB)讀入數組,查詢從「隨機磁盤 IO」變為「內存二分」,速度提升 **10-50 倍**。
  2. 單例/連接池複用:長運行進程(Swoole、Workerman、PHP-FPM 持久進程)實例化一次,全局複用,避免重複打開文件。
  3. 批量查詢優化:對 IP 列表排序後查詢,利用磁盤順序讀取特性(未緩存索引時)。
  4. 定期更新數據庫:從 GitHub 鏡像 或官網下載最新 qqwry.dat,建立自動更新腳本。

對比:在線 API vs 離線數據庫

維度離線 qqwry.dat在線 API (高德/百度/IP2Location)
延遲微秒級 (本地內存)毫秒級 (網絡 RTT)
併發承載極高 (無鎖讀取)受限於 API 配額/頻率
數據鮮度需手動更新 (周/月)實時
隱私/合規數據不出服務器IP 發送給第三方
IPv6 支援❌ 僅 IPv4✅ 多數支援
成本零成本免費額度後付費

對於高併發、強隱私、IPv4 為主的內部系統,**離線 qqwry.dat + 內存索引** 是性價比最高的選擇;需 IPv6 或極高精度(街道級)時,結合在線 API 作為補充。

copyright © 萬盛學電腦網 all rights reserved