Sunday, June 29, 2008

IP / CIDR calculation in MySQL, PHP and JavaScript

IP / CIDR calculation in MySQL, PHP and JavaScript

MySQL
inet_aton
inet_ntoa


select inet_aton('127.0.0.1');
select inet_ntoa(2130706433);
last IP = first IP + (2^(32-mask)) - 1
select inet_ntoa(inet_aton('213.144.132.248') + (pow(2, (32-29))-1));

-
Javascript
function ip2long(ip) {
var ips = ip.split('.');
var iplong = 0;
with (Math) {
iplong = ips0*pow(256,3)+ips1*pow(256,2)+ips2*pow(256,1)+ips3*pow(256,0)
}
return iplong;
}

function long2ip(l) {
with (Math) {
var ip1 = floor(l/pow(256,3));
var ip2 = floor((l%pow(256,3))/pow(256,2));
var ip3 = floor(((l%pow(256,3))%pow(256,2))/pow(256,1));
var ip4 = floor((((l%pow(256,3))%pow(256,2))%pow(256,1))/pow(256,0));
}
return ip1 + '.' + ip2 + '.' + ip3 + '.' + ip4;
}


function lastIP(ip, mask) {
return ip + (Math.pow(2, (32 - mask))-1);
}



-


/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/


No comments: