awoodland has asked for the wisdom of the Perl Monks concerning the following question:

I have a socket, called $socket which i made with
$socket = IO::Socket::INET->new(LocalPort => $port, Listen => 10, Proto => 'tcp', Reuse => 1);

my question is, How do I find out what IP address it is listening on?

Replies are listed 'Best First'.
Re: My IP address
by blakem (Monsignor) on Sep 09, 2001 at 13:19 UTC
    This script finds your ip address:
    #!/usr/bin/perl -wT use strict; use POSIX qw(uname); use IO::Socket; my $hostname = (uname)[1]; my $ipbin = gethostbyname($hostname) or die "Couldn't resolve $hostname : $!"; my $ip = inet_ntoa($ipbin); print "$hostname => $ip\n"; =output cobalt.blakem.com => 64.94.194.149
    Though your question might be about machines with multiple ip addresses.... can't really tell.

    -Blake

Re: My IP address
by kschwab (Vicar) on Sep 09, 2001 at 18:04 UTC
    Since you didn't specify anything, it's listening on INADDR_ANY, or all the ip addresses on the machine. This is typically represented as 0.0.0.0. Had you specified LocalAddr, it could have been something more specific. It may be more interesting to check the ip address on the new IO::Socket::INET object you get after an accept().

    The programmatic way to discover this is via getsockname(). (Just FYI, getpeername() does the same for the remote end).

    IO::Socket provides some nice shortcuts to get just the info you want, rather than the whole struct sockaddr. It also provides niceties that return ip addresses as text strings, rather than a packed format. In your case, IO::Socket::INET::sockhost makes sense:

    See IO::Socket::INET for more info.

    my ($hostaddr_as_a_string)=$socket->sockhost(); print "Local addr is $hostaddr_as_a_string\n";
    While I'm at at, a FAQ about getsockname is "Why would anyone need it ? Since I'm doing the bind(), shouldn't I know what I'm listening on ?"

    I'm sure there's other answers, but I think the most typical one is that some socket based programs inherit the socket from a parent process that forked. The child, therefore, may not have called the bind itself.

    Update: In retrospect, I suppose that it's more common to use getsockname() on a socket returned from accept(). ( From a listening socket on INADDR_ANY ).