Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

How do I get the local internet IP address?

by Anonymous Monk
on Jan 23, 2001 at 07:26 UTC ( #53660=categorized question: print w/replies, xml ) Need Help??
Contributed by Anonymous Monk on Jan 23, 2001 at 07:26 UTC
Q&A  > network programming

Answer: How do I get the local internet IP address?
contributed by tirwhan

This question is usually asked to find out which IP address the local host uses to connect to a remote one. One important thing to realise in this context is that there is no such thing as a host's IP address. Network interfaces have IP addresses, not hosts, and a single network interface can have many (virtual) IP addresses. The operating system's routing subsystem decides which network interface and IP address to use to connect to a remote machine. If your machine only has one external network interface, and this interface only has one IP address then this IP address is commonly called the machine's address, but that is inaccurate. For example, if the machine is connected to a VPN via a virtual interface it will use this interface's IP address to connect to another machine on the VPN, not the external IP address.

Usually the best fail-safe way to find the "local Internet IP address" is to actually establish a network connection to the remote host and then find out which IP address is being used on the local side. For example:

use IO::Socket::INET; my $sock = IO::Socket::INET->new( PeerAddr=> "", PeerPort=> 80, Proto => "tcp"); my $localip = $sock->sockhost;
Answer: How do I get the local internet IP address?
contributed by kschwab

Works if Sys::Hostname comes up with a resolvable hostname.

use Sys::Hostname qw(hostname); # not strictly necessary; exports it b +y default use Socket; my($addr) = inet_ntoa( (gethostbyname(hostname()))[4] ); print "$addr\n";
Answer: How do I get the local internet IP address?
contributed by tye

FAQ. See How do I find out my hostname, domainname, or IP address?

Answer: How do I get the local internet IP address?
contributed by arhuman

Non portable, return the ip address of all hosts found in /etc/hosts...

while (@adrs=(gethostent())[4]) { for my $value (@adrs) { print join '.',unpack('C4',$value); print "\n"; } }

Answer: How do I get the local internet IP address?
contributed by Perlbotics

Sometimes, firewalls block a connection setup to a well known IP address. When using the resolve mechanisms it is assumed that the information — e.g. in /etc/hosts, name servers, etc. — is maintained, accessible, trusted, and valid.

If both methods fail, a look at the actual IP configuration might help. As a (okay, maybe not the very) last resort, esp. when multiple interfaces and IPMP is concerned, examining the output of /sbin/ifconfig -a (*NIX), or ipconfig /all (WIN*) might work to reveal the interfaces currently plumbed and configured. At least the OS's tool which is responsible to configure the IPs should be able to give a reliable answer. The fragile part is to rely on the outputs layout.
You might need to change the locale language (e.g. LANG, LC_ALL) beforehand.

Illustrative code that was tested on Solaris 10, openSUSE 10.2, and OS X:
#!/usr/bin/perl use strict; use Data::Dumper; my $interface; my %IPs; foreach ( qx{ (LC_ALL=C /sbin/ifconfig -a 2>&1) } ) { $interface = $1 if /^(\S+?):?\s/; next unless defined $interface; $IPs{$interface}->{STATE}=uc($1) if /\b(up|down)\b/i; $IPs{$interface}->{IP}=$1 if /inet\D+(\d+\.\d+\.\d+\.\d+)/i; } print Dumper(\%IPs); __END__ $VAR1 = { 'qfe0' => { 'IP' => '', 'STATE' => 'UP' }, 'qfe1' => { 'IP' => '', 'STATE' => 'UP' }, 'hme0' => { 'IP' => '', 'STATE' => 'DOWN' }, 'lo0' => { 'IP' => '', 'STATE' => 'UP' } };
Answer: How do I get the local internet IP address?
contributed by betterworld

This is probably the least portable version because it uses Linux-specific data structures, but for the fun of it and for completeness, I'll post it:

#!/usr/bin/perl use strict; use warnings; require 'sys/'; use Socket; my %interfaces; my $max_addrs = 30; socket(my $socket, AF_INET, SOCK_DGRAM, 0) or die "socket: $!"; { my $ifreqpack = 'a16a16'; my $buf = pack($ifreqpack, '', '') x $max_addrs; my $ifconf = pack('iP', length($buf), $buf); # This does the actual work ioctl($socket, SIOCGIFCONF(), $ifconf) or die "ioctl: $!"; my $len = unpack('iP', $ifconf); substr($buf, $len) = ''; %interfaces = unpack("($ifreqpack)*", $buf); unless (keys(%interfaces) < $max_addrs) { # Buffer was too small $max_addrs += 10; redo; } } for my $addr (values %interfaces) { $addr = inet_ntoa((sockaddr_in($addr))[1]); } use Data::Dumper; print Dumper \%interfaces;

The output is:

$VAR1 = { 'eth0:1' => '', 'eth0' => 'x.y.z.128', 'eth0:3' => '', 'eth0:4' => '', 'eth0:2' => 'x.y.z.62', 'lo' => '' };

(I've stripped the public addresses.)

I've successfully tested it on Debian etch and sarge.

Answer: How do I get the local internet IP address?
contributed by Anonymous Monk

Same as above, but you can use this to resolve any address through the DNS setup (/etc/resolv.conf or the /etc/hosts file).

use Socket; my $hostname = "somehost.ext"; my @addr = inet_aton($hostname) or return "Unknown or invalid host."; my($a,$b,$c,$d) = unpack('C4', $addr(0)); #change the $addr() to brackets, this form filters brackets out. my $ip = "$a.$b.$c.$d"; print $ip;
Answer: How do I get the local internet IP address?
contributed by AgentM

If you simply want to send yourself something, use the loopback address (

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    [ambrus]: Corion: well Prima::Object says something like that the cleanup method will send an onDestory message and that you can't get more messages after cleanup, or something.
    [Corion]: ambrus: Yeah - I don't think the deep source dive will be necessary if things are implemented as simple as they could be :)) And hopefully I won't need (more) timely object destruction. I can update the screen at 60Hz and hopefully even do HTTP ...
    [Corion]: ... transfers in the background. Now that I think about it, this maybe even means that I can run the OpenGL filters on Youtube input :)
    [ambrus]: Corion: I mentioned that the unix event loop of Prima always wakes up at least once every 0.2 seconds. Have you found out whether the win32 event loop of Prima does that too?
    [Corion]: ambrus: Hmm - I would assume that the onDestroy message is sent from the destructor and doesn't go through the messageloop, but maybe it is sent when a window gets destroyed but all components are still alive...
    [ambrus]: Corion: partly deep source dive, partly just conservative coding even if it adds an overhead.
    [Corion]: ambrus: Hmm - no, I haven't looked at wakeup intervals ... I wonder why it should want to wakeup periodically because it gets a lot of messages from the Windows message loop (on Windows obviously)
    [ambrus]: (Alternately a deep source dive and then rewrite that event loop to make it better, and then as a bonus you get an idle method.)
    [ambrus]: The 0.2 seconds wakeup is likely a workaround for some bug, but I can't guess what bug that is.
    [ambrus]: It's been there since Prima 1.00 iirc

    How do I use this? | Other CB clients
    Other Users?
    Others chanting in the Monastery: (7)
    As of 2016-12-09 10:29 GMT
    Find Nodes?
      Voting Booth?
      On a regular basis, I'm most likely to spy upon:

      Results (150 votes). Check out past polls.