Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

How do I get the local internet IP address?

( #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
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others taking refuge in the Monastery: (4)
    As of 2016-04-30 23:04 GMT
    Find Nodes?
      Voting Booth?
      :nehw tseb si esrever ni gnitirW

      Results (441 votes). Check out past polls.