I would like to generate a random IP adress.
7 Answers
On 64-bit PHP:
long2ip(rand(0, 4294967295));
Working in 2021 in any supported PHP version (7.4 and 8.0).
Note: since almost any machine is x64 nowadays and the development of 32-bit operating systems is being abandoned, if this is not working you may probably want to download the x64 version of PHP.
3 Comments
Check the mt_rand func .
You'll probably want to run this :
<?php
$randIP = mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255) . "." . mt_rand(0, 255);
?>
Comments
$ip = long2ip(mt_rand());
This way is slightly more readable.
1 Comment
127.255.255.255 since mt_rands max value is 2147483647. If you pass a higher value, it returns false.According to some answeres here, I decided to add an answere to correct some mistakes that was made...
mt_rand(int $min, int $max);
Some samples used this function with a max values of 4294967295. But this function only supports a max value of 2147483647, whats actually the half. Passing a higher number will return false. Using this function whitout passing anything will also only give the half of the needed value. So
long2ip(mt_rand());
would return a max ip of 127.255.255.255
To have the full range you need some like:
long2ip(mt_rand()+mt_rand());
But even in this sample you will maximum get 255.255.255.254. So to have a full range you need a third mt_rand().
The correct way to get the total range in a short hand code is:
$ip = long2ip(mt_rand()+mt_rand()+mt_rand(0,1));
Beware to use + and not *. Because max value * max value would return 255.255.255.255 as expacted but the chance to get a lower ip isn't that good anymore. To keep good chances using * you could do some like:
$ip = long2ip((mt_rand()*mt_rand(1,2))+mt_rand(0,1));
3 Comments
For 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());