简体   繁体   中英

How to select an IP from an IP Range?

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.

$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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM