Home > Blockchain >  How to select an IP from an IP Range?
How to select an IP from an IP Range?

Time:12-09

My goal is to create a function that selects an IP Address from a give IP Range.

At the moment I am using this function:

function IPRange($start, $end) {
    $start = ip2long($start);
    $end = ip2long($end);

    return array_map('long2ip', range($start, $end));
}

I know that this function only generates the IP Range, but how can I select an IP after that range is generated?

Example: I have the given IP Range 93.118.193.0 - 93.118.193.255. From this range, automatically get one (for example: 93.118.193.83) and set it as "remote-address" attribute. If the IP is already set, get another one randomly (so that two "remote-address" are identical).

I tried to use safelong2ip("127.0.0.1/32");, but everytime it generates me the same IP: 0.0.0.93.

CodePudding user response:

$start = '10.3.63.2';
$end = '15.8.254.79';

var_dump(long2ip(random_int(ip2long($start), ip2long($end))));

ip2long gives you a simple number. Just generate a random number in a range, and turn that back into an IP with long2ip.

  • Related