socket.gethostbyaddr( os.environ['REMOTE_ADDR'] error

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at
Tue Jan 10 01:42:17 EST 2012

Am 09.01.2012 23:35 schrieb Dominic Binks:
> On 1/9/2012 2:19 PM, Νικόλαος Κούρας wrote:
>> Can you please explain me what the [0] in host =
>> socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] does at the end?
>> Why not just host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )
>> instead? what is the need of [0] ?
> The address database can have multiple names for the same IP address so
> gethostbyaddr returns a list - [0] being the first item in the list (and
> usually considered the canonical name)

It might be noteworthy that it is nowadays preferrable to use 
getaddrinfo() instead. This way, you get all acceptable IP addresses, 
not only IPv4 ones. And then, you should not only try this one entry - 
[0] -, but iterate over all of them until you have a connection.

BTW: This behaviour might be useful with gethostbyaddr() as well - if 
the first one returned has gone away, you have the chance to reach the 
2nd one...


More information about the Python-list mailing list