Pages

Friday, September 27, 2013

OpenWRT DHCP Listing

I have openwrt on my router and my dhcp listing is constantly displayed in some erratic order. As far as I can tell it's not sorted in any fashion, it's just kinda tossed in there (maybe clients that refresh their lease don't move in the file)

It looks like this...


Kinda makes me irritated because there's no web controls to sort the listing and I like to see my clients by IP address (OCD or Autism, who knows).

So, I wrote this...

Ahhhh... Much better!

#!/usr/bin/php-cli
<?php
    foreach (file("/tmp/dhcp.leases") as $line) {
        $fields = explode(" ", $line);
        $data[] = Array($fields[0], $fields[1], $fields[2], $fields[3]);
    }

    function cmp($a, $b) {
        $a_long = sprintf('%u', ip2long($a[2]));
        $b_long = sprintf('%u', ip2long($b[2]));

        return ($a_long > $b_long);
    }

    usort($data, 'cmp');

    foreach ($data as $var=>$value) {
        foreach ($value as $subvar=>$subvalue) {
            echo "\t\t" . $subvalue;
        }
        echo "\n";
    }
?>

EDIT:

I've done this inside the openwrt LUCI by modifying "/usr/lib/lua/luci/view/admin_status/index.htm"

I added
function ipaddr(tmp) {
 var a = tmp.split(".");

 for (var i = 0; i < a.length; i++) {
  while (a[i].length < 3) {
   a[i] = "0" + a[i];
  }
 }

 return a[0] + a[1] + a[2] + a[3];
}

function displayIP(tmp) {
 var a = tmp.split(".");

 for (var i = 0; i < a.length; i++) {
  while (a[i].length < 3) {
   a[i] = "0" + a[i];
  }
 }
 return a[0] + "." + a[1] + "." + a[2] + "." + a[3];
}
above the lines
<% if has_dhcp then %>
var ls = document.getElementById('lease_status_table');
if (ls)
and then I added
info.leases.sort(
function(a, b) {
return (ipaddr(a.ipaddr) < ipaddr(b.ipaddr) ? -1 : 
      (ipaddr(a.ipaddr) > ipaddr(b.ipaddr) ? 1: 0));
}
);
above the lines
for( var i = 0; i < info.leases.length; i++ )
{
 var timestr;

 if (info.leases[i].expires <= 0)
  timestr = '<%:expired%>';
 else

And TAADAA!