What's a good way to get my IP from Python?
Michael P. Reilly
arcege at shore.net
Tue Aug 10 19:50:54 CEST 1999
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.
# 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)
ipaddr, port = s.getsockname()
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?
More information about the Python-list