简体   繁体   中英

IP and Subnet to Start IP End IP

So I have an IP with a Subnet like: 8.8.8.0/24

How can I convert this to 8.8.8.0 and 8.8.8.255 (actually their ip2long resultants)

In PHP and JavaScript

I will assume you will also need for other mask like 8,16,...

ip="8.8.8.0/24"
  1. extract each parts ip_array=ip.match(/(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)\\/(\\d+)/) //js regex

  2. convert to number ip_num = (ip[1]<<24)+(ip[2]<<16)+(ip[3]<<8)+(+ip[4]) //# 0x08080800

  3. mask=(1<<(32-ip[5]))-1 //# 0xFF

  4. ip_num | mask ip_num | mask will be 0x080808FF which is 8.8.8.255

  5. ip_num & (0xffffffff ^ mask) will be 0x08080800 which is 8.8.8.0

  6. you need to convert ip_num back to ip string back

To generate a list of IP addresses from slash notation:

$range = "8.8.8.0/24";
$addresses = array();

@list($ip, $len) = explode('/', $range);

if (($min = ip2long($ip)) !== false) {
  $max = ($min | (1<<(32-$len))-1);
  for ($i = $min; $i < $max; $i++)
    $addresses[] = long2ip($i);
}

var_dump($addresses);

To check if an IP address falls within a range:

$checkip = "8.8.8.154";
$range = "8.8.8.0/24";

@list($ip, $len) = explode('/', $range);

if (($min = ip2long($ip)) !== false && !is_null($len)) {
  $clong = ip2long($checkip);
  $max = ($min | (1<<(32-$len))-1);
  if ($clong > $min && $clong < $max) {
    // ip is in range
  } else {
    // ip is out of range
  }
}

Just treat each IP like a base-256 number with 4 digits. For example,

8.8.8.0   == 8 * 256^3 + 8 * 256^2 + 8 * 256^1 + 0 * 256^0   == 134744064
8.8.8.1   == 8 * 256^3 + 8 * 256^2 + 8 * 256^1 + 1 * 256^0   == 134744065
8.8.8.1   == 8 * 256^3 + 8 * 256^2 + 8 * 256^1 + 2 * 256^0   == 134744066
...
8.8.8.255 == 8 * 256^3 + 8 * 256^2 + 8 * 256^1 + 255 * 256^0 == 134744319

I think this may be sort of what you're getting at. It will determine all IPs in a given range.

$ip = '8.8.8.0';
$mask = 24;

$ip_enc = ip2long($ip);
# convert last (32-$mask) bits to zeroes
$curr_ip = $ip_enc | pow(2, (32-$mask)) - pow(2, (32-$mask));
$ips = array();

for ($pos = 0; $pos < pow(2, (32-$mask)); ++$pos) {
    $ips []= long2ip($curr_ip + $pos);
}

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