newbe: tuple

Tim Chase python.list at tim.thechases.com
Wed Jun 14 10:45:55 EDT 2006


> ip = socket.gethostbyaddr(socket.gethostname())
> 
> ip then becomes a tuple and takes on three values. I am trying to pull the
> value of ip[2] which when printed displays:
> ['10.5.100.17'].
> 
> I want this ip that is being returned, but I would like it as a string,
> without the [' and ']. Any idea how I would trim this down?

Well, what you're getting back is the list of possible IP 
addresses for your machine.  The "['w.x.y.z']" is simply the 
repr() of that list.  A single machine can have multiple IP 
addresses, so ip[2] returns them as a list.  You can either use

	ip_addresses = ip[2]
	my_ip_address = ip_addresses[0]
	# this is the same as
	# my_ip_address = ip[2][0]
	# only slightly clearer to read

or your code can graciously accomodate them the way they were 
designed for:

	for ip_address in ip_addresses:
		print ip_address

This allows you to deal with the possibility that the machine has 
more than one IP address assigned to it.  I'm not at my OpenBSD 
box, but it's got at least three interfaces in it, and each one 
has its own IP address assigned to it.  I presume that ip[2] 
would return a list of three strings in its case, something like

	['192.168.3.14', '10.3.14.15', '172.16.3.14']

HTH,

-tkc






More information about the Python-list mailing list