I would like to generate a random IP adress.
php $randIP = mt_rand(0, 255) . "." . mt_rand(0, 255) .
The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.
First, click on your Start Menu and type cmd in the search box and press enter. A black and white window will open where you will type ipconfig /all and press enter. There is a space between the command ipconfig and the switch of /all. Your ip address will be the IPv4 address.
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.
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);
?>
$ip = long2ip(mt_rand());
This way is slightly more readable.
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));
You could also get a pool of valid IPs from your own webserver logs, if you have any:
cat /var/log/apache2/access_log |cut -d' ' -f1|egrep -v '[a-z]'|sort|uniq > lotsofip.txt
and then in php:
$ips = file('lotsofip.txt');
echo $ips[array_rand($ips)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With