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

I am using IO::Socket::INET and IO::Socket::SSL (depending on whether I need a plain-text connection or an SSL connection) to connect to a remote server. I am using a hostname and not an IP address to specify the remote server to connect to.

However, the DNS server lists several IP addresses for that hostname (round-robin DNS). Since the DNS server can be changed at anytime to add or remove IP addresses, it is important that I use the hostname.

The problem that I am having is how to determine which IP address I am currently connected to. I am trying to avoid doing a DNS lookup myself on the hostname, and then using the returned IP address for the connection... I am not even sure how to do that, but I may have to go down that road if I can't find a more elegant solution to the problem.

Anyways, is there a way to determine the remote IP address of a currently connected session in Perl?

Thanks,
Zucan

  • Comment on How to determine IP address of a remote connection?

Replies are listed 'Best First'.
Re: How to determine IP address of a remote connection?
by fglock (Vicar) on Dec 02, 2004 at 16:06 UTC

    Use one of the IO::Socket::INET documented methods

    METHODS sockaddr () Return the address part of the sockaddr structure for the socket sockport () Return the port number that the socket is using on the local host sockhost () Return the address part of the sockaddr structure for the socket i +n a text form xx.xx.xx.xx peeraddr () Return the address part of the sockaddr structure for the socket o +n the peer host peerport () Return the port number for the socket on the peer host. peerhost () Return the address part of the sockaddr structure for the socket o +n the peer host in a text form xx.xx.xx.xx
      Okay, thanks...

      I tried peerhost() and got what I was looking for:

        my $IP = $SMTP->peerhost();
        print "Connected to $IP\n";
      

      It prints the IP address of the remote host as expected, and each run of the program shows a different IP, which all map back correctly to the original hostname.

      Thanks for the help!
      Zucan