Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

MAC Address of An Interface

by amt (Monk)
on Sep 08, 2004 at 02:45 UTC ( #389265=perlquestion: print w/replies, xml ) Need Help??

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

Gentlemen, I am working on a script that needs to report the MAC address of an interface, as well as other specific information, back to a subnet allocation database. The purpose of this is to automate the entry of this information into the new database format.

Is there a default module for ifconfig(8)? I have found Net::Interface, but that isn't a default module. Filesystem size is a major issue, so module installation isn't an option unless absolutely crucial. Is there a module in the IO class of modules, or a hack, considered system() and parsing, but looking for something neater.


Replies are listed 'Best First'.
Re: MAC Address of An Interface
by tachyon (Chancellor) on Sep 08, 2004 at 05:29 UTC

    Did you say use Inline 'C'?

    #!/usr/bin/perl use Inline 'C'; get_mac('eth0'); __END__ __C__ #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> void get_mac( char *iface ) { int s; struct ifreq buffer; memset(&buffer, 0x00, sizeof(buffer)); s = socket(PF_INET, SOCK_DGRAM, 0); strcpy(buffer.ifr_name, iface); ioctl(s, SIOCGIFHWADDR, &buffer); close(s); for( s = 0; s < 5; s++ ) printf("%.2X:", (unsigned char)buffer.ifr_hwaddr.sa_data[s]); printf("%.2X\n", (unsigned char)buffer.ifr_hwaddr.sa_data[s]); }

    Easy to compile it into a command line C widget you call with backtics so you don't need Inline. Just drop the perl part, add int main(int argc,char *argv[]){get_mac(argv[1]);return 0;}, compile it and then call it from perl like $mac = `widget $iface`



      Thank you tachyon, it turns out that I will probably have to implement this application in C, for proprietary concerns.

      Thanks to all those who made suggestions.

Re: MAC Address of An Interface
by hsinclai (Deacon) on Sep 08, 2004 at 03:00 UTC
    Did you say Linux?

    Maybe parse it out of the ifconfig output itself?

    perl -e '$if=eth0; $mac=(split(/\s+/,qx!/sbin/ifconfig $if!))[4]; prin +t $mac;'

    On BSD you'd pull out the "ether" line of ifconfig..
Re: MAC Address of An Interface
by JSchmitz (Canon) on Sep 08, 2004 at 04:01 UTC
    did you say Solaris? try something like this:
    #!/usr/bin/perl -w use Net::Telnet open(FH, "host_list_file") || die "Yikes $!"; while (<FH>) { $t = new Net::Telnet(Timeout => 2810, Prompt => '/%/', Host => 'ip address' ); $t->login( "user", "password" ); { $t->cmd( "ndd /dev/arp arp_cache_report" ); } $t->close;

    happy hunting
Re: MAC Address of An Interface
by Rhys (Pilgrim) on Sep 08, 2004 at 12:00 UTC
    Did you say SNMP?

    Or, if you want to get the MAC addresses of a whole bunch of devices at once (including any IP aliases that might be set up), you can do:

    # DO NOT USE THIS WITHOUT YOUR NET ADMINS' PERMISSION! # YOU PROBABLY WON'T HURT ANYTHING, BUT YOU'LL UPSET THEM # IF YOU DON'T ASK FIRST. use SNMP; # Requires Net-SNMP package from SourceForge. use strict; my $community; my $defgate; my $mib; my $sess; my $var; my $vb; my %ARP; my %sessparms; # Initialize SNMP. $SNMP::use_sprint_value = 1; # The MIB objects we need are pre-loaded in Net-SNMP. &SNMP::initMib(); $community = 'public'; # Use your read-only community here. $defgate = ''; # Use your default gateway here. $sessparms{'DestHost'} = $defgate; $sessparms{'Community'} = $community; $sessparms{'Version'} = '2'; # Recommended. $sess = new SNMP::Session(%sessparms); if ( not defined $sess ) { die "Couldn't open SNMP session to $defgate.\n"; } $mib = 'ipNetToMediaPhysAddress'; # ARP table. $vb = new SNMP::Varbind([$mib]); GETARP: while ( $vb->tag eq $mib ) { $var = $sess->getnext($vb); if ( $sess->{ErrorNum} ) { print "Got $sess->{ErrorStr} querying ARP table on $defgate.\n"; last GETARP; } if ( $vb->iid =~ /(\d+\.\d+\.\d+\.\d+)$/ ) { $ARP{$1} = $var; } } # Not the best sort for this, but hey... foreach ( sort keys %ARP ) { print sprintf "MAC for %-15s is %17s.\n", $_, $ARP{$_}; }


    1. As it says, this is unwise to do if you don't have the permission of whoever is running the router. You'll set off all sorts of security alarms, the DoHS will drag you away and you'll never be heard from again. {:-O
    2. If you have a bunch of machines running this script against the same router at the same time, you can bog down its CPU (although I've never seen a single querier create such a problem, and most routers set management traffic to a low priority anyway).
    3. The format of the instance numbers ($vb->iid) changes from router to router, so you may want to add a print "IID is ", $vb->iid, "\n"; in there to see for yourself if things aren't working.



    Update: Gave a shorter while loop with a better test. Fixed arg to SNMP::Session() (a hash, not a hashref). Added test for successful session creation.

    Update: Added proper 'header' line to fit the rest of the thread. ;-)

      ++ for platform-independent code. I actually took a few moments to try to come up with a shell-out solution, but wouldn't you know it, the command-line tools all work differently on different platforms. I'd ++ you a dozen times more, if I could.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://389265]
Approved by ikegami
Front-paged by grinder
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (2)
As of 2021-04-22 03:07 GMT
Find Nodes?
    Voting Booth?

    No recent polls found