robster has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, wonder if somebody can shed some light!

Using Fedora Core 4 box, perl 5.8.6, have a small script that I'd like to find default gateway of a dynamically allocated ip address.

This command:
netstat -r | grep ^default | awk '{print $2}'
works fine from a bash prompt, and gives me address output:
217.xx.xx.xx

I thought I could do this in perl:
my $GATEWAY_ADDR=`netstat -r | grep ^default | awk '{print $2}'`;

but it dunt work, It won't give me JUST the gateway address like the first one it spits out the whole line thus:
default 217.xx.xx.xx 0.0.0.0 UG 0 0 0 ppp0

I'd be the first to admit not very good at perl, wonder if somebody could give me a pointer?

Thanks in advance,
Kind regards, Rob.

2006-02-10 Retitled by g0n, as per Monastery guidelines
Original title: 'get default gatway'

Replies are listed 'Best First'.
Re: get default gateway
by InfiniteSilence (Curate) on Feb 09, 2006 at 21:18 UTC
    #!/usr/bin/perl -w use strict; while(<DATA>) { if (!/^default/){next}; my @stuff = split /\s+/; print $stuff[1]; } 1; __DATA__ Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Ifac +e 255.255.255.255 0.0.0.0 255.255.255.255 UH 40 0 0 wlan +0 192.168.1.0 0.0.0.0 255.255.255.0 U 40 0 0 wlan +0 127.0.0.0 0.0.0.0 255.0.0.0 U 40 0 0 lo default 192.168.1.1 0.0.0.0 UG 40 0 0 wlan +0

    Celebrate Intellectual Diversity

Re: get default gateway
by zentara (Cardinal) on Feb 09, 2006 at 21:23 UTC
    #!/usr/bin/perl -w $|++; open( N, "route |") or die "$!\n"; my @out = (<N>); foreach my $line (@out){ my @words = split(/\s+/,$line); if($words[0] eq 'default'){ print "default-> $words[1]\n"; } }

    I'm not really a human, but I play one on earth. flash japh
      remember that with route, ifconfig and so, unless you are root, you need the path. it's not a bad idea to use the path with this sort of app in any case.

        Actually unless you have /sbin in PATH you should use the full path.</pedant>

Re: get default gateway
by jcc (Sexton) on Feb 15, 2006 at 20:40 UTC
    I don't think anyone commented on why your script was not producing the desired results. The $2 value in the awk command (used to print the second column of input) was being interpreted by perl as a variable... thus you were passing awk '{print }' to the shell. Escaping the '$' would give you the desired results.
    my $GATEWAY_ADDR=`netstat -r | grep ^default | awk '{print \$2}'`;