\r\n<?php
class WhoisQuery {
/** TLD => WHOIS 服务器映射 (部分常用) */
private static $servers = [
'com' => 'whois.internic.net',
'net' => 'whois.internic.net',
'org' => 'whois.pir.org',
'cn' => 'whois.cnnic.cn',
'cc' => 'whois.nic.cc',
'tv' => 'whois.tv',
'io' => 'whois.nic.io',
'ai' => 'whois.nic.ai',
'dev' => 'whois.nic.google',
'app' => 'whois.nic.google',
'xyz' => 'whois.nic.xyz',
'top' => 'whois.nic.top',
'club'=> 'whois.nic.club',
'site'=> 'whois.nic.site',
'online'=> 'whois.nic.online',
'shop'=> 'whois.nic.shop',
'store'=> 'whois.nic.store',
'tech'=> 'whois.nic.tech',
'space'=> 'whois.nic.space',
'website'=> 'whois.nic.website',
'biz' => 'whois.biz',
'info'=> 'whois.afilias.net',
'name'=> 'whois.nic.name',
'mobi'=> 'whois.dotmobiregistry.net',
'asia'=> 'whois.nic.asia',
'me' => 'whois.nic.me',
'co' => 'whois.nic.co',
'us' => 'whois.nic.us',
'ca' => 'whois.cira.ca',
'de' => 'whois.denic.de',
'uk' => 'whois.nic.uk',
'fr' => 'whois.nic.fr',
'jp' => 'whois.jprs.jp',
'kr' => 'whois.kr',
'eu' => 'whois.eu',
'gov' => 'whois.nic.gov',
'edu' => 'whois.educause.edu',
'mil' => 'whois.nic.mil',
'int' => 'whois.iana.org',
'arpa'=> 'whois.iana.org',
];
/**
* 查询域名 WHOIS
* @param string $domain 域名 (可含 https://、www.)
* @return string|false 原始响应文本,失败返回 false
*/
public static function query(string $domain): string|false {
// 1. 规范化域名
$domain = strtolower(trim($domain));
$domain = preg_replace('/^https?:\/\//i', '', $domain);
$domain = preg_replace('/^www\./i', '', $domain);
$domain = explode('/', $domain)[0]; // 取主机部分
$domain = trim($domain);
// 2. 提取 TLD
$parts = explode('.', $domain);
$tld = end($parts);
// 3. 查找服务器
$server = self::$servers[$tld] ?? null;
if (!$server) {
// 兜底:尝试 IANA 根服务器
$server = 'whois.iana.org';
}
// 4. Socket 连接查询
$fp = @fsockopen($server, 43, $errno, $errstr, 10);
if (!$fp) {
error_log("WHOIS connect failed: $server ($errstr)");
return false;
}
stream_set_timeout($fp, 10);
fwrite($fp, $domain . "\r\n");
$response = '';
while (!feof($fp)) {
$response .= fgets($fp, 4096);
}
fclose($fp);
return $response;
}
}
// ========== 使用示例 ==========
$domains = ['google.com', 'github.io', 'cnnic.cn', 'example.xyz'];
foreach ($domains as $d) {
echo "=== $d ===\n";
$result = WhoisQuery::query($d);
echo $result ?: "查询失败\n";
echo "\n";
}
stream_set_timeout 防止卡死原始响应格式因注册局而异,常见字段:
Domain Name: EXAMPLE.COM
Registry Domain ID: 123456_DOMAIN_COM-VRSN
Registrar: Example Registrar
Creation Date: 2020-01-01T00:00:00Z
Expiration Date: 2025-01-01T00:00:00Z
Name Server: NS1.EXAMPLE.COM
Status: clientTransferProhibited
可用正则提取关键字段,或接入成熟库 phpwhois/phpwhois。
WHOIS 数据受 ICANN 政策、GDPR 等法规约束。
- 不得大规模抓取转售
- 隐私保护模式下个人信息会被遮蔽
- 查询结果仅供技术运维、安全研究、品牌保护等合法用途
将 WhoisQuery 类纳入工具库,即可快速集成域名查询、过期监控、品牌保护等功能。