萬盛學電腦網

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

PHP 實現 IP 歸屬地查詢:基於純真數據庫 (qqwry.dat) 完整實現

前言

IP 地址歸屬地查詢是日誌分析、用戶畫像、安全審計的基礎功能。PHP 通過解析「純真 IP 數據庫」(qqwry.dat) 可實現高效、離線、無第三方依賴的 IP 定位。本文提供完整的類實現,採用二分查找算法,支援 IPv4 地址與域名解析。

數據庫文件結構解析

qqwry.dat 採用定長索引區 + 變長記錄區結構:

  • 文件頭 (8 字節): 第一條索引偏移量 (4B) + 最後一條索引偏移量 (4B)
  • 索引區 (每條 7 字節): 起始 IP (4B) + 指向記錄區偏移 (3B)
  • 記錄區: 結束 IP (4B) + 國家/地區字符串 + 省份/城市字符串 (以 \0 結尾,支援重定向壓縮)

核心類實現 (IPLocation.php)

<?php
/**
 * 純真 IP 數據庫解析類
 * 依賴 qqwry.dat 文件 (請從官方或可信來源獲取最新版)
 */
class IPLocation {
    private $fp;
    private $firstIndexOffset;
    private $lastIndexOffset;
    private $totalRecords;

    const RECORD_LENGTH = 7; // 索引區每條長度
    const FLAG_COUNTRY_REDIRECT = 1;
    const FLAG_AREA_REDIRECT = 2;

    public function __construct(string $datFile = 'qqwry.dat') {
        if (!file_exists($datFile)) {
            throw new RuntimeException("IP 數據庫文件不存在: $datFile");
        }
        $this->fp = fopen($datFile, 'rb');
        $this->firstIndexOffset = $this->readLong();
        $this->lastIndexOffset  = $this->readLong();
        $this->totalRecords = ($this->lastIndexOffset - $this->firstIndexOffset) / self::RECORD_LENGTH;
        register_shutdown_function([$this, 'close']);
    }

    public function close(): void {
        if (is_resource($this->fp)) fclose($this->fp);
    }

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

    /** 讀取 3 字節偏移地址 (補齊 1 字節解包) */
    private function readOffset(): int {
        $bytes = fread($this->fp, 3) . "\x00";
        return unpack('V', $bytes)[1];
    }

    /** 讀取以 \0 結尾的字符串 */
    private function readString(): string {
        $str = '';
        while (($char = fread($this->fp, 1)) !== "\x00") {
            $str .= $char;
        }
        return $str;
    }

    /** 讀取標誌位 */
    private function readFlag(): string {
        return fread($this->fp, 1);
    }

    /** IP 字符串轉大端序 4 字節 (用於比較) */
    private function ipToBytes(string $ip): string {
        return pack('N', ip2long($ip)); // N = big endian unsigned long
    }

    /** 解析記錄區地址信息 (處理重定向) */
    private function parseRecord(int $offset): array {
        fseek($this->fp, $offset);
        $flag = $this->readFlag();
        $country = $area = '';

        switch (ord($flag)) {
            case self::FLAG_COUNTRY_REDIRECT: // 國家重定向
                $countryOffset = $this->readOffset();
                fseek($this->fp, $countryOffset);
                $flag2 = $this->readFlag();
                if (ord($flag2) == self::FLAG_AREA_REDIRECT) {
                    $areaOffset = $this->readOffset();
                    $area = $this->readStringAt($areaOffset);
                } else {
                    fseek($this->fp, -1, SEEK_CUR);
                    $area = $this->readString();
                }
                $country = $this->readStringAt($countryOffset + 4); // 跳過重定向標誌+偏移
                break;

            case self::FLAG_AREA_REDIRECT: // 僅地區重定向
                $areaOffset = $this->readOffset();
                $area = $this->readStringAt($areaOffset);
                $country = $this->readString();
                break;

            default: // 無重定向
                fseek($this->fp, -1, SEEK_CUR);
                $country = $this->readString();
                $area = $this->readString();
                break;
        }
        return ['country' => $country, 'area' => $area];
    }

    /** 在指定偏移讀取字符串 */
    private function readStringAt(int $offset): string {
        $cur = ftell($this->fp);
        fseek($this->fp, $offset);
        $str = $this->readString();
        fseek($this->fp, $cur);
        return $str;
    }

    /** 二分查找 IP 所在索引 */
    private function binarySearch(string $ipBytes): ?int {
        $low = 0;
        $high = $this->totalRecords - 1;

        while ($low <= $high) {
            $mid = (int)(($low + $high) / 2);
            fseek($this->fp, $this->firstIndexOffset + $mid * self::RECORD_LENGTH);
            $startIp = strrev(fread($this->fp, 4)); // 索引區存小端序,轉大端比較
            $recordOffset = $this->readOffset();
            fseek($this->fp, $recordOffset);
            $endIp = strrev(fread($this->fp, 4));

            if ($ipBytes < $startIp) {
                $high = $mid - 1;
            } elseif ($ipBytes > $endIp) {
                $low = $mid + 1;
            } else {
                return $this->firstIndexOffset + $mid * self::RECORD_LENGTH;
            }
        }
        return null;
    }

    /** 公開查詢介面 */
    public function query(string $ipOrDomain): ?array {
        $ip = gethostbyname($ipOrDomain); // 域名自動解析
        if ($ip === $ipOrDomain && !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            return null; // 無效 IP/域名
        }
        $ipBytes = $this->ipToBytes($ip);
        $indexOffset = $this->binarySearch($ipBytes);
        if ($indexOffset === null) return null;

        // 讀取索引區的記錄區偏移
        fseek($this->fp, $indexOffset + 4); // 跳過起始 IP
        $recordOffset = $this->readOffset();
        fseek($this->fp, $recordOffset);
        $startIp = long2ip($this->readLong());
        $endIp = long2ip($this->readLong());
        $location = $this->parseRecord($recordOffset + 8); // 跳過結束 IP

        return [
            'ip' => $ip,
            'start_ip' => $startIp,
            'end_ip' => $endIp,
            'country' => $location['country'],
            'area' => $location['area'],
        ];
    }
}

使用範例

<?php
require_once 'IPLocation.php';

try {
    $ipLocator = new IPLocation(__DIR__ . '/qqwry.dat');

    $tests = [
        '8.8.8.8',           // Google DNS
        '114.114.114.114',   // 114 DNS
        'www.baidu.com',     // 域名自動解析
        '192.168.1.1',       // 內網 IP (查無結果)
    ];

    foreach ($tests as $target) {
        $result = $ipLocator->query($target);
        if ($result) {
            printf("IP: %-15s | 範圍: %s - %s | 國家: %s | 區域: %s\n",
                $result['ip'], $result['start_ip'], $result['end_ip'],
                $result['country'] ?: '未知', $result['area'] ?: '未知');
        } else {
            echo "$target -> 未找到歸屬地信息\n";
        }
    }
} catch (Exception $e) {
    echo "錯誤: " . $e->getMessage();
}

輸出示例

IP: 8.8.8.8         | 範圍: 8.8.8.0 - 8.8.8.255 | 國家: 美國 | 區域: 加利福尼亞州山景市谷歌公司
IP: 114.114.114.114 | 範圍: 114.114.114.0 - 114.114.114.255 | 國家: 中國 | 區域: 江蘇省南京市電信
IP: www.baidu.com   | 範圍: 180.101.49.0 - 180.101.49.255 | 國家: 中國 | 區域: 北京市百度網訊科技有限公司
IP: 192.168.1.1     -> 未找到歸屬地信息

效能優化建議

  1. 單例模式: 實例化一次,全局複用,避免重複打開文件句柄。
  2. 內存映射 (mmap): 大流量場景可用 mmap 將 .dat 映射到內存,消除 I/O 開銷 (需 sysvshm 或 shmop 擴展)。
  3. 數據庫更新: 定期 (如每月) 從 純真官網 下載最新 qqwry.dat 替換舊文件。
  4. IPv6 支援: 純真庫僅支援 IPv4,IPv6 需使用 ip2location、MaxMind GeoIP2 等商業/開源庫。

結語

通過封裝二分查找與重定向解析邏輯,PHP 即可高效實現離線 IP 歸屬地查詢。此方案零外部依賴、響應極快 (亞毫秒級),適合日誌實時分析、訪問控制、內容分發等場景。建議將上述類納入專案公共庫,並配合定時任務自動更新數據庫,保證查詢準確性。

copyright © 萬盛學電腦網 all rights reserved