Linux: Find my IP address using Perl at a shell prompt

by on October 18, 2007 · 11 comments· LAST UPDATED October 18, 2007

in , ,

Q. How do I find out my IP address assigned to eth0 or ra0 interface using perl?

A. If you need to know the IP address of the UNIX / Linux machine you are running on, use the following perl one liner. Perl don't have any inbuilt facility but combination of ifconfig command ans shell pipes you can craft something as follows to display your system IP address:

Find my IP address using Perl One liner and shell pipes

Type the following command at a shell prompt:

ifconfig -a | perl -ne 'if ( m/^\s*inet (?:addr:)?([\d.]+).*?cast/ ) { print qq($1\n); exit 0; }'
Tweet itFacebook itG+ itDownload PDF versionFound an error/typo on this page?

{ 11 comments… read them below or add one }

1 raj October 23, 2007 at 1:26 pm

thanks really helpful!


2 Leigh November 7, 2007 at 10:42 pm

For non-root users, put /sbin/ in front of the ifconfig line, so it becomes

/sbin/ifconfig -a | perl -ne 'if ( m/^\s*inet (?:addr:)?([\d.]+).*?cast/ ) { print qq($1\n); exit 0; }'


3 ashish June 16, 2008 at 1:24 pm


i’m trainne in system admin i working on thin client

i’ve tried the code above then i get ip addr but when i simple use ifconfig

i got the error COMMAND NOT FOUND
can u tell y


4 ian November 18, 2008 at 3:38 pm

You can use gethostbyname in the Socket package to do the work for you:

use Socket;
use strict;

my ($host) = `hostname`;

my $iaddr = gethostbyname($host);

if (defined($iaddr)) {
print (inet_ntoa($iaddr), “\n”);
} else {
die (“ipaddr failed to get IP address for $host\n”);


5 Akshatha June 23, 2009 at 4:12 am

very useful.. saved lot of my time :) thanks


6 poisonbit November 28, 2009 at 3:46 am

I’ve made a bash function based in these post and comments.


7 Deepti March 5, 2010 at 8:18 pm

very useful really


8 Peter Burkholder October 3, 2011 at 9:44 pm

Thanks for figuring my ifconfig regex parsing for me. Saved me a few minutes, and it works for Mac and Linux.


9 Snap ( October 9, 2011 at 7:41 am

use LWP::UserAgent;
$browser = LWP::UserAgent -> new() or die “problem dog?\n”;
$browser -> agent(“niggaBrowzaaa”);
sub encontrarIP{
$result = $browser->request(HTTP::Request->new(GET=>$_[0]));
$content = $result->content;
$urlLength = @url;

for ($i=0;$i didn’t worked.\n”;
print “\nNONE of them worked WTF !!\n”;
print “worst luck than me ?? \n”;
print “nah ! you probably aren’t connected\n”;



10 alex toderita October 11, 2013 at 11:37 am
/sbin/ip -o -4 addr show eth0 | perl -lane 'print $1 if /h(d. E)//'

More verbose… for the kill…

perl -MSocket -e 'require "sys/"; socket($sock, PF_INET, SOCK_STREAM, (getprotobyname("tcp"))[2]); $buf = pack("a256", "eth0"); ioctl($sock, SIOCGIFADDR(), $buf); @addr= unpack("x20 C4", $buf); print join(".", @addr),"n";'


11 Paul Rice April 27, 2014 at 8:21 pm

God bless you, Sir! lol


Leave a Comment

Tagged as: , , , , , , , , , ,

Previous Faq:

Next Faq: