1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#!/usr/bin/perl -w
# (C) Copyright 2001 Enrico Zini <zinie@cs.unibo.it>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# This script prints the macaddres of the network interface correspoding to the
# given address.
use strict;
# Print usage informations and exit
sub usage ()
{
print qq{Usage: $0 <hostname> [interface]
Print the macaddress corresponding to the network interface
of the address <hostname>, reached through network interface [interface]. If
omitted, [interface] defaults to 'eth0'
};
exit 1;
}
# Notify that the MAC was not found. Prints a message only if running
# interactive.
sub notfound (@)
{
(-t STDOUT) && print @_, "\n";
exit 1;
}
# Paths to the commands we use (they are not in users path by default)
my $arp = '/usr/sbin/arp';
my $arping = '/usr/sbin/arping';
# Get commandline options
my $host = shift @ARGV or usage();
my $interface = (shift @ARGV or 'eth0');
#
# First try using arp -a to see if we have it cached
# (more efficient, no network output)
#
open (IN, "$arp -a '$host'|") or die "Can't run $arp: $!";
while (<IN>)
{
if (/at (\S+) .+ on $interface/ && $1 ne '<incomplete>')
{
print "$1\n";
exit 0;
}
}
close (IN);
notfound("No match for $host with $arp through $interface, and $arping not found") if not -x $arping;
#
# No match with arp, let's try to discover it with arping
# (We use the iputils-arping version of arping here.)
#
open (IN, "$arping -f -c 1 -w 3 -I $interface '$host'|") or die "Can't run $arping: $!";
while (<IN>)
{
if (/\[([^]]+)\]/)
{
print "$1\n";
exit 0;
}
}
notfound("No match for $host with neither $arp nor $arping through $interface");
|