Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP and Subnet to Start IP End IP

Tags:

javascript

php

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

like image 407
steven Avatar asked Jan 08 '10 06:01

steven


People also ask

What is my start IP address and end IP address?

Start IP: Type an IP address to serve as the start of the IP range that DHCP will use to assign IP addresses to all LAN devices connected to the router. End IP: Type an IP address to serve as the end of the IP range that DHCP will use to assign IP addresses to all LAN devices connected to the router.

What is the first IP in a subnet called?

Network address The network IP address is the first address of the subnet. You calculate it by converting the IP address and subnet mask to binary and performing a bitwise AND logical operation. A router uses this address to forward traffic to the correct network.


2 Answers

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

like image 191
YOU Avatar answered Oct 05 '22 14:10

YOU


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
  }
}
like image 39
Sacred Socks Avatar answered Oct 05 '22 14:10

Sacred Socks