What's a good way to get my IP from Python?
Michael P. Reilly
arcege at shore.net
Tue Aug 10 13:50:54 EDT 1999
Aaron Rhodes <aarhodes at cisco.com> wrote:
: Hello,
: 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?
-Arcege
More information about the Python-list
mailing list