Posted By

eno on 12/28/10


Tagged

network interface address IPv4 ioctl


Versions (?)

the most reliable and correct method to get network interface address in Linux using Perl


 / Published in: Perl
 

This method doesn't rely on parsing 'ifconfig' tool output, and should work in any Linux distribution, but also could work in other POSIX environments. The function returns a string with IPv4 address or 'undef' if it's not possible.

  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use Socket;
  5. require 'sys/ioctl.ph';
  6.  
  7. print get_interface_address('eth0');
  8.  
  9. sub get_interface_address
  10. {
  11. my ($iface) = @_;
  12. my $socket;
  13. socket($socket, PF_INET, SOCK_STREAM, (getprotobyname('tcp'))[2]) || die "unable to create a socket: $!\n";
  14. my $buf = pack('a256', $iface);
  15. if (ioctl($socket, SIOCGIFADDR(), $buf) && (my @address = unpack('x20 C4', $buf)))
  16. {
  17. return join('.', @address);
  18. }
  19. }

Report this snippet  

You need to login to post a comment.