BBB File /usr/local/sbin/ifdisplay

From Wiki
Jump to: navigation, search

This script is called from /etc/rc.local when the BBB starts up, and also from the BBB File /usr/local/sbin/ipwatchd daemon when an IP address changes on a network interface.

It could probably be cleaned up, but it's not called very often, and performance is hardly critical.

#!/bin/sh

showConfigSingle ()
{
  # wlan0     IEEE 802.11bgn  Mode:Master  Tx-Power=20 dBm   
  #           Retry  long limit:7   RTS thr:off   Fragment thr:off
  #           Power Management:off
  #                            
  #  eth0      no wireless extensions.
  #
  mode=`iwconfig $1 2>/dev/null | perl -e '
    $/ = undef;
    $a = <>;
    ($mode) = $a =~ /Mode:(\w+)/;
    $mode =~ s/Master/AP/;
    $mode =~ s/Managed/Client/;
    print $mode || "None";
  '`

  # 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000\    link/ether c8:a0:30:b1:18:a2 brd ff:ff:ff:ff:ff:ff
  # 2: eth0    inet 172.16.0.128/16 brd 172.16.255.255 scope global eth0
  # 2: eth0    inet6 fe80::caa0:30ff:feb1:18a2/64 scope link \       valid_lft forever preferred_lft forever
  
  ip -o addr | perl -se '
    $/ = undef; 
    $a = <>; 
    print "  Intf: $intf\n";
    ($mac) = $a =~ /${intf}.*ether (.*?) /; 
    print "Status: " . (defined ($mac) ? "Up" : "Down") . "\n";
    print "  Mode: " . $mode . "\n" unless ($mode =~ /None/);
    if (defined $mac)
    {
      ($addr) = $a =~ /${intf}.*inet (.*?)\//; 
      ($mask) = $a =~ /${intf}.*inet.*?(\d+) brd/;
      ($bcast) = $a =~ /${intf}.*brd (.*?) /; 
      $mask = ~((1 << (32 - $mask)) - 1);
      print "   MAC: $mac\n";
      print "  Addr: $addr\n";
      printf ("  Mask: %d.%d.%d.%d\n", ($mask >> 24) & 0xff, ($mask >> 16) & 0xff, ($mask >> 8) & 0xff, $mask & 0xff);
      print " Bcast: $bcast\n";
    }
  ' -- -intf=$1 -mode=$mode >>$2
  
  # default via 172.16.0.254 dev eth0 
  # 172.16.0.0/16 dev eth0  proto kernel  scope link  src 172.16.0.128 
  # 192.168.7.0/30 dev usb0  proto kernel  scope link  src 192.168.7.2 
  # 192.168.17.0/24 dev wlan0  proto kernel  scope link  src 192.168.17.1 
  
  ip route | perl -se '
    $/ = undef;
    $a = <>;
    ($src) = $a =~ /${intf}.*src (.*)$/m;
    if (defined $src)
    {
      ($gateway) = $a =~ /default via (.*?) /;
      print " Route: $gateway\n";
    }
  ' -- -intf=$1 >>$2

  echo >>$2
}

showConfig ()
{
  tmp=`mktemp`

  for intf in eth0 wlan0; do
    showConfigSingle $intf $tmp
  done

  lpr < $tmp
  rm -f $tmp
}

showConfig