Sorting on IP address
Sorting on IP address
nowords
Posts: 8Questions: 0Answers: 0
Maybe odd, but it was handy to use this sorting on IP address in CIDR notation.
for example, we have a subnet/size like: 111.16.32.0/24
[code]
function dot2num(dot) {
var d = dot.split('.');
return ((((((+d[0]) * 256) + (+d[1])) * 256) + (+d[2])) * 256) + (+d[3]);
}
function clean_subnet_size (ip) {
ip = ip.replace(/\/[0-9][0-9]/, "");
return ip;
}
$.fn.dataTableExt.oSort['string-ip-asc'] = function (x, y) {
x = clean_subnet_size(x);
x = dot2num(x);
y = clean_subnet_size(y);
y = dot2num(y);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
$.fn.dataTableExt.oSort['string-ip-desc'] = function (x, y) {
x = clean_subnet_size(x);
x = dot2num(x);
y = clean_subnet_size(y);
y = dot2num(y);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
[/code]
And do not forget specify column type for sorting in table initiation.
Second column is the column for ip sorting.
[code]
"aoColumns": [
null,
{ "sType": 'string-ip' },
null
],
[/code]
for example, we have a subnet/size like: 111.16.32.0/24
[code]
function dot2num(dot) {
var d = dot.split('.');
return ((((((+d[0]) * 256) + (+d[1])) * 256) + (+d[2])) * 256) + (+d[3]);
}
function clean_subnet_size (ip) {
ip = ip.replace(/\/[0-9][0-9]/, "");
return ip;
}
$.fn.dataTableExt.oSort['string-ip-asc'] = function (x, y) {
x = clean_subnet_size(x);
x = dot2num(x);
y = clean_subnet_size(y);
y = dot2num(y);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
$.fn.dataTableExt.oSort['string-ip-desc'] = function (x, y) {
x = clean_subnet_size(x);
x = dot2num(x);
y = clean_subnet_size(y);
y = dot2num(y);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
[/code]
And do not forget specify column type for sorting in table initiation.
Second column is the column for ip sorting.
[code]
"aoColumns": [
null,
{ "sType": 'string-ip' },
null
],
[/code]
This discussion has been closed.
Replies
Allan