17.7. Identifying the Other End of a SocketProblemYou have a socket and want to identify the machine at the other end. SolutionIf you're only interested in the IP address of the remote machine, use: use Socket; $other_end = getpeername(SOCKET) or die "Couldn't identify other end: $!\n"; ($port, $iaddr) = unpack_sockaddr_in($other_end); $ip_address = inet_ntoa($iaddr); If you want its actual host name, use: use Socket; $other_end = getpeername(SOCKET) or die "Couldn't identify other end: $!\n"; ($port, $iaddr) = unpack_sockaddr_in($other_end); $actual_ip = inet_ntoa($iaddr); $claimed_hostname = gethostbyaddr($iaddr, AF_INET); @name_lookup = gethostbyname($claimed_hostname) or die "Could not look up $claimed_hostname : $!\n"; @resolved_ips = map { inet_ntoa($_) } @name_lookup[ 4 .. $#ips_for_hostname ]; Discussion
For a long time, figuring out who connected to you was considered more straightforward than it really is. The
Not really. That's only half the solution. Because a name lookup goes to the name's owner's DNS server and a lookup of an IP addresses goes to the address's owner's DNS server, you have to contend with the possibility that the machine that connected to you is giving incorrect names. For instance, the machine
To avoid this problem, we take the (possibly deceitful) name returned by $packed_ip = gethostbyname($name) or die "Couldn't look up $name : $!\n"; $ip_address = inet_ntoa($packed_ip);
So far we've assumed we're dealing with an Internet domain application. You can also call Even this level of paranoia and mistrust isn't enough. It's still possible for people to fake out DNS servers they don't directly control, so don't use hostnames for identification or authentication. True paranoiacs and misanthropes use cryptographically-secure methods. See Also
The
Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|