Getting local IP address...
Pekka Pessi
ppessi at hut.fi
Fri Jul 21 14:35:56 EDT 2000
mfletch at tpresence.com.bbs@openbazaar.net (Mike Fletcher) writes:
>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. The more common socket-module-based approach (see
>Deja) can be confused if you have multiple network interface cards, but is
>still portable (i.e. if you only have a single network interface card, it
>should work on all system supporting the socket module).
I have been using a piece of code like this:
def gethostaddr(dst = '224.0.1.41'):
s = socket.socket(AF_INET, SOCK_DGRAM)
try:
s.connect((dst, 7))
(host, port) = s.getsockname()
s.close()
if host != '0.0.0.0':
return host
except error:
pass
return socket.gethostbyname(socket.gethostname())
As an added bonus, no extra connection - UDP just binds the socket
to your local address. If not, like MS Winsock, it tries true and
tried gethostbyname(gethostname()) trick.
--
Pekka.Pessi at hut.fi
More information about the Python-list
mailing list