phpippreg-match

How to define range of IP numbers to a variable


I want to set a range of IP numbers to a name in php

How can I write below line in correct way in PHP?

$block_renge = array("192.168.*.*", "10.10.*.*");

i want * to be any number (0-255) . could someone please help me the way i could do this

Then I check the IP with below code:

if ( ( in_array( $ip_address, $block_renge ) ) ) {
// do some stuff
//$ip_address is the customer ip address

maybe with preg_match we could done this?

UPDATE Senario changed and it be done with check "as_name" of the ip address.

curl "https://api.myip.com/?&output=json" | jq
# respond could be differ due the api
{
  "asn": "15169",
  "asn_name": "GOOGLE, US",
  "asn_range": "8.8.8.0/24",
  "ip": "8.8.8.8"
}

Solution

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

    You can then use

    if (in_array($ip, $ip_range)){ //...