IP Address

Donn Cave donn at u.washington.edu
Thu Apr 27 12:05:46 EDT 2000

Quoth "Fredrik Lundh" <fredrik at pythonware.com>:
| Richard Chamberlain wrote:
| > Is there a way of returning the IP address of the machine that a =
| script is
| > running on?
| here's one way to do it:
| ip = socket.gethostbyname(socket.gethostname())

Took the words out of my mouth.  But I would add, while this is
the right thing for general use, there are situations where it's
not reliable, where it might return an IP address that is in some
sense valid but not useful.  Consider this as an alternative for
those situations:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('123.345.567.789', 53))
ip, localport = s.getsockname()

This establishes an IP connection to a remote host.  It happens to
be to the DNS service port -- thinking this remote host would be the
primary DNS for your host, chosen because it's one of those network
identities without which little else has meaning.  But any host and
service will do, the point is that you know it will be ``out there''
and accepting connections.  The getsockname() on this connection
tells you what your IP address is in the context of ``out there'',
as opposed to one of perhaps several IP addresses that are or were
valid in some back door network shown in /etc/hosts.  It also will
get your network up first, if you're in an ``on demand'' situation
where the address is dynamically assigned.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu

More information about the Python-list mailing list