王新阳

wangxinyang

php随机生成有效的公网ipv4地址

//随机生成有效的公网ipv4地址
function generateRandomPublicIPv4() {
	// 排除的IP范围(局域网、保留地址等)
	$excludedRanges = [
		['0.0.0.0', '0.255.255.255'],	   // 当前网络
		['10.0.0.0', '10.255.255.255'],	 // 私有网络
		['100.64.0.0', '100.127.255.255'],  // Carrier-grade NAT
		['127.0.0.0', '127.255.255.255'],   // 环回地址
		['169.254.0.0', '169.254.255.255'], // 链路本地
		['172.16.0.0', '172.31.255.255'],   // 私有网络
		['192.0.0.0', '192.0.0.255'],	   // IETF协议分配
		['192.0.2.0', '192.0.2.255'],	   // TEST-NET-1
		['192.88.99.0', '192.88.99.255'],   // 6to4中继
		['192.168.0.0', '192.168.255.255'], // 私有网络
		['198.18.0.0', '198.19.255.255'],   // 网络基准测试
		['198.51.100.0', '198.51.100.255'], // TEST-NET-2
		['203.0.113.0', '203.0.113.255'],   // TEST-NET-3
		['224.0.0.0', '239.255.255.255'],   // 组播地址
		['240.0.0.0', '255.255.255.254'],   // 保留地址
		['255.255.255.255', '255.255.255.255'] // 广播地址
	];
	foreach($excludedRanges as &$row){
		$row[0]=ip2long($row[0]);
		$row[1]=ip2long($row[1]);
	}
	
	// 生成随机IP直到找到有效的公网IP
	do {
		// 生成随机IP
		$ipLong = mt_rand(ip2long('1.0.0.0'), ip2long('223.255.255.255'));
		$ip = long2ip($ipLong);
		
		$isValid = true;
		
		// 检查是否在排除范围内
		foreach ($excludedRanges as $range) {
			list($start,$end)=$range;
			
			if ($ipLong >= $start && $ipLong <= $end) {
				$isValid = false;
				break;
			}
		}
		
		// 额外检查:排除以0或255结尾的地址(通常有问题)
		$parts = explode('.', $ip);
		if ($parts[3] == 0 || $parts[3] == 255) {
			$isValid = false;
		}
		
	} while (!$isValid);
	
	return $ip;
}
2025-04-02
2025-04-04 星期五 农历三月初七