Return to Snippet

Revision: 38180
at December 28, 2010 09:45 by eno

Initial Code
use strict;
use warnings;
use Socket;
require 'sys/';

print get_interface_address('eth0');

sub get_interface_address
	my ($iface) = @_;
	my $socket;
	socket($socket, PF_INET, SOCK_STREAM, (getprotobyname('tcp'))[2]) || die "unable to create a socket: $!\n";
	my $buf = pack('a256', $iface);
	if (ioctl($socket, SIOCGIFADDR(), $buf) && (my @address = unpack('x20 C4', $buf)))
		return join('.', @address);
	return undef;

Initial URL

Initial Description
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.

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

Initial Tags

Initial Language