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
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
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);
}
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