Getting local IP address...

db3l at fitlinxx.com.bbs db3l at fitlinxx.com.bbs
Mon Jul 17 21:30:03 EDT 2000


Mike Fletcher <mfletch at tpresence.com> writes:

> import socket
> def getLocalHostIP( remote = ("www.python.org", 80)):
> 	'''Get the "public" address of the local machine, i.e.
> 	that address which is connected to the general internet.
> 	Code by Donn Cave, posted to comp.lang.python'''
> 	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> 	s.connect( remote )
> 	ip, localport = s.getsockname()
> 	s.close()
> 	return ip
>
> That is actually from a Deja posting, seems to be fairly portable, doesn't
> rely on parsing obscure Unix command responses, is readable, and is
> generally quite reliable.

But has a pretty large (IMHO) negative that you are making a wasted
network connection to an external server that has to spend time
setting up and tearing down TCP with you for no reason.  That seems a
pretty high overhead to pay just to determine what is essentially a
locally configured piece of information.  If you are in charge of your
own server that you are using I suppose that's one thing, but it seems
a big waste if you're connecting to someone else's.

Unfortunately, really determining a local configured address just
isn't that portable a thing from my experience.  Probably the closest
would be the SIOCGIFCONF IOCtl (for Unix systems) as previously
posted.  There is an Windows socket IOCtl that is similar
(SIO_ADDRESS_LIST_QUERY), but I'm not sure how best to get to it from
Python, aside from something like a CallDLL approach.

While without an alternative that is portable as the above example
makes it hard to come out too strong against it, I did want to point
out that while it may be portable and readable, it has negatives on
the network side in terms of wasted connections.  I built backbones in
a prior life, and I sort of cringe to think of tons of user code
suddenly starting to do stuff like the above :-)

--
-- David
--
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list