Clean way to get one's network IP address?

Jean-Paul Calderone exarkun at divmod.com
Wed Nov 21 17:47:09 CET 2007


On Wed, 21 Nov 2007 16:15:43 +0100, Gilles Ganault <nospam at nospam.com> wrote:
>Hello
>
>I need to get the local computer's IP address, ie. what's displayed
>when running "ifconfig" in Linux:
>
># ifconfig
>eth0      Link encap:Ethernet  HWaddr 00:15:58:A1:D5:6F
>          inet addr:192.168.0.79  Bcast:192.168.0.255
>Mask:255.255.255.0
>
>I know about socket.gethostbyname, but this relies on what's in
>/etc/hosts, and I'd rather have a more independent solution.
>
>What would be a good way to do this?

You can generally get the local address which will be used for traffic
to a particular host by getting ready to send traffic to it with a UDP
socket:

    >>> from socket import socket, SOCK_DGRAM, AF_INET
    >>> s = socket(AF_INET, SOCK_DGRAM)
    >>> s.connect(('google.com', 0))
    >>> s.getsockname()
    ('192.168.1.113', 43711)

Jean-Paul



More information about the Python-list mailing list