#!/usr/bin/perl -T

# Based on the tablewalk.pl example from the libsnmp-perl
# as copyleft as the above example.
#
# This is what I use at home on my speedtouch ADSL router.
# Looks up the given interface index by the hardwired description (pppoe) 
# in the interface table,
# and then uses this index to fetch the externally visible IP address
# from the IP address table. Prints the IP address on the STDOUT.
#
# --Vassilii Khachaturov <vassilii@tarunz.org>

use SNMP 1.8;

my $DEBUG = 0;

my $pppoe_ifdescr = 'pppoe';
my $host = shift || 'speedtouch';
my $comm = shift || 'public';

my $sess = new SNMP::Session ( DestHost => $host, Version => 1, Community => $comm );

my $vars = new SNMP::VarList([ifIndex],[ifDescr]);
my $pppoe_ifIndex = '';
for (@vals = $sess->getnext($vars);
     $vars->[0]->tag =~ /ifIndex/       # still in table
     and not $sess->{ErrorStr};          # and not end of mib or other error
     @vals = $sess->getnext($vars)) {
     print "   $vals[0] \"$vals[1]\"\n" if $DEBUG;
	 if ($vals[1] =~ /$pppoe_ifdescr/oi) {
		 $pppoe_ifIndex = $vals[0];
		 last;
	 }
}

die "Didn't find an interface with $pppoe_ifdescr in its description!"
	unless $pppoe_ifIndex;

$vars = new SNMP::VarList([ipAdEntAddr],[ipAdEntIfIndex]);

my $pppoe_ipaddr = '';
for (@vals = $sess->getnext($vars);
     $vars->[0]->tag =~ /ipAdEntAddr/       # still in table
     and not $sess->{ErrorStr};          # and not end of mib or other error
     @vals = $sess->getnext($vars)) {
     print "   ($vals[1]) $vals[0]\n" if $DEBUG;
	 if ($vals[1] == $pppoe_ifIndex) {
		 $pppoe_ipaddr = $vals[0];
		 last;
	 }
}
exit(1) unless $pppoe_ipaddr;

print "$pppoe_ipaddr\n";
