user198729
user198729

Reputation: 63636

How to create a range of IP addresses?

Suppose the input is:

222.123.34.45 and 222.123.34.55

then I need to output the ip address in between them:

222.123.34.45 222.123.34.46 ... 222.123.34.55

Upvotes: 3

Views: 2839

Answers (3)

Stanislav
Stanislav

Reputation: 31

You can use the function; $ipStr = "192.168.1.0/255";

 function getIpsArrayFromStrRange($ipStr) {
    $ipsArray = array();
    //validate ip and check range existing
    $regexp = '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\d{1,3}))?$/';
    $matches = array();
    if(preg_match($regexp,$ipStr,$matches)){


        //if it is a range
        if(isset($matches[6])){
            $min_ip = min($matches[4],$matches[6]);
            $max_ip = max($matches[4], $matches[6]);
            for($i=$min_ip; $i<=$max_ip; $i++){
                $ipsArray[] = "$matches[1].$matches[2].$matches[3].$i";
            }   
        }else{
            $ipsArray[] = $ipStr;
        }
        return $ipsArray;
    }else{
        return false;
    }
}

Upvotes: 0

Alana Storm
Alana Storm

Reputation: 166066

Leveraging PHP's type flexibility

Leveraging the fact that IP Addresses are actually numbers (may do weird things on

$ip2 = '222.123.34.55';

$ips = array();
for($i=ip2long($ip);$i<=ip2long($ip2);$i++)
{
    $ips[] = long2ip($i);
}

print_r($ips);

Upvotes: 0

cletus
cletus

Reputation: 625057

Use ip2long() and long2ip():

function ip_range($from, $to) {
  $start = ip2long($from);
  $end = ip2long($to);
  $range = range($start, $end);
  return array_map('long2ip', $range);
}

The above turns the two IP addresses into numbers (using PHP core functions), creates a range of numbers and then turns that number range into IP addresses.

If you want them separated by spaces just implode() the result.

Upvotes: 20

Related Questions