What's a good way to get my IP from Python?

Donn Cave donn at u.washington.edu
Tue Aug 10 22:04:39 CEST 1999


"Michael P. Reilly" <arcege at shore.net> writes:
| Aaron Rhodes <aarhodes at cisco.com> wrote:
| : Does anyone know of a really good way to determine the
| : IP address of the ethernet cards on a Linux system
| : using Python only (i.e. no C code/parsing external binaries, etc.) ?
|
| Hopefully this is portable, but my work PC is down and don't have
| access to a Mac; but theoretically it should be.
|
|   import socket
|   def my_ipaddr(interface_hostname=None):
|     # give the hostname of the interface you want the ipaddr of
|     hostname = interface_hostname or socket.gethostname()
|     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|     s.bind(hostname, 0)
|     ipaddr, port = s.getsockname()
|     s.close()
|     return ipaddr  # returns 'nnn.nnn.nnn.nnn' (StringType)
|
| You aren't connecting to anything so this _should_ work even if you are
| not on a network at the time (PPP), the interface just needs to be
| plumbed and initialized.  The begged question would be: how do you get
| the hostnames of multiple interfaces from within Python.  Anyone have a
| good answer for that?

I ran into this problem in a PPP situation, and I had to crank harder
than that.  Of course multiple networks is part of the problem (I had
separate local and dial-up networks, both via PPP.)  But for me, even
with only one network, in a dynamic situation like most PPP services,
I got a valid IP only when I attempt to connect to something via that
network.  I more or less arbitrarily chose to connect to my primary
DNS service.

The recent thread on ifconfig interface is germane here.  If the ifconfig
ioctls work on your platform (i.e., UNIX), you can retrieve all kinds
of information about network interfaces, but I don't know if it has any
answer for valid PPP latency worries as discussed above, and at present
it would require some no-portability-guarantees struct packing (see thread
for more.)

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




More information about the Python-list mailing list