Getting local IP address...

Mike Fletcher mfletch at tpresence.com
Mon Jul 17 13:40:43 EDT 2000


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. 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).

Enjoy yourselves,
Mike




More information about the Python-list mailing list