From roderick@argon.org  Wed May 31 17:39:03 2000
To: perlfaq-suggestions@perl.com
From: Roderick Schertler <roderick@argon.org>
Subject: learn IP address without gethostbyname()
Date: Wed, 31 May 2000 17:39:03 -0400
Message-ID: <19873.959809143@eeyore.ibcinc.com>

perlfaq9 recommends getting your IP address by doing a lookup on your
hostname.  Here's a more direct method which is often right:

    use Socket;

    socket S, PF_INET, SOCK_DGRAM, 0                    or die $!;
    connect S, scalar sockaddr_in 1, "\x01\x01\x01\x01" or die $!;
    my $packed_address = (sockaddr_in getsockname S)[1];
    my $text_address = inet_ntoa $packed_address;
    close S;

    print "$text_address\n";

I believe this will actually give you the address of the interface your
machine would use to route to the given IP address (1.1.1.1 here).  If I
use this on a multihomed host and give it an address on an alternate LAN
it tells me the machine's address on that network instead.

--
Roderick Schertler
roderick@argon.org
