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
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.
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.
I will assume you will also need for other mask like 8,16,...
ip="8.8.8.0/24"
extract each parts ip_array=ip.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d+)/)
//js regex
convert to number ip_num = (ip[1]<<24)+(ip[2]<<16)+(ip[3]<<8)+(+ip[4])
//# 0x08080800
mask=(1<<(32-ip[5]))-1
//# 0xFF
ip_num | mask
will be 0x080808FF which is 8.8.8.255
ip_num & (0xffffffff ^ mask)
will be 0x08080800 which is 8.8.8.0
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With