我想生成一个随机 IP 地址。
7 回答
在64 位PHP 上:
long2ip(rand(0, 4294967295));
在 2021 年使用任何受支持的 PHP 版本(7.4 和 8.0)。
注意:由于现在几乎所有机器都是 x64 并且正在放弃 32 位操作系统的开发,如果这不起作用,您可能需要下载 x64 版本的 PHP。
检查mt_rand 函数。
你可能想运行这个:
<?php
    $randIP = mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255);
?>
$ip = long2ip(mt_rand());
这种方式更具可读性。
根据这里的一些答案,我决定添加一个答案来纠正所犯的一些错误......
mt_rand(int $min, int $max);
一些示例使用此函数,最大值为4294967295。但是这个函数只支持最大值2147483647,实际上是一半。传递更高的数字将返回false。在不传递任何内容的情况下使用此函数也只会给出所需值的一半。所以
long2ip(mt_rand());
将返回一个最大 ip127.255.255.255
要拥有完整的范围,您需要一些类似的东西:
long2ip(mt_rand()+mt_rand());
但即使在这个示例中,您也会最大程度地得到255.255.255.254. 因此,要拥有完整的范围,您需要第三个mt_rand().
以简写代码获得总范围的正确方法是:
$ip = long2ip(mt_rand()+mt_rand()+mt_rand(0,1));
注意使用 + 而不是 *。因为max value*max value会255.255.255.255按预期返回,但获得较低 ip 的机会不再那么好。为了保持使用 * 的好机会,您可以执行以下操作:
$ip = long2ip((mt_rand()*mt_rand(1,2))+mt_rand(0,1));
如果有的话,您还可以从自己的网络服务器日志中获取有效 IP 池:
cat /var/log/apache2/access_log |cut -d' ' -f1|egrep -v '[az]'|sort|uniq >lotsofip.txt
然后在php中:
$ips = file('lotsofip.txt');    
echo $ips[array_rand($ips)];
对于 IPV6:
<?php
function randomizeFromList(array $list)
{
    if (empty($list)) {
        return null;
    }
    $randomIndex = random_int(0, count($list) - 1);
    return $list[$randomIndex];
}
function generateIpv6(): string
{
    $ipv6String = '';
    //IPV6 Pattern ([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}
    $hexSymbols = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
    ];
    $randomLength2 = random_int(1, 7);
    for ($i = 0; $i < $randomLength2; ++$i) {
        $ipv6String    .= randomizeFromList($hexSymbols);
        $randomLength1 = random_int(0, 4);
        for ($j = 0; $j < $randomLength1; ++$j) {
            $ipv6String .= randomizeFromList($hexSymbols);
        }
        $ipv6String .= ':';
    }
    $randomLength3 = random_int(0, 4);
    for ($k = 0; $k < $randomLength3; ++$k) {
        $ipv6String .= randomizeFromList($hexSymbols);
    }
    return $ipv6String;
}
echo(generateIpv6());
$ip = intval(rand()%255).'.'.intval(rand()%255).'.'.intval(rand()%255).'.'.intval(rand()%255);