Windows getting local ip address

Fredrik Lundh fredrik at pythonware.com
Wed Mar 22 16:55:49 CET 2006


"SolaFide" wrote:

> On Linux, it is a simple matter to get the local ip address with
> system.os("ifconfig >> /tmp/ip"); ip=open("/tmp/ip").readlines(), etc.

    ip = os.popen("ifconfig").readlines()

is a bit more convenient.

> How can I do this with Windows?

the command is called "ipconfig" in windows.

there's also

    >>> import socket
    >>> socket.gethostbyname(socket.gethostname())
    '1.2.3.4'
    >>> socket.gethostbyname_ex(socket.gethostname())
    ('bender.shiny.com', ['bender'], ['1.2.3.4'])
    >>> socket.getaddrinfo(socket.gethostname(), 0)
    [(2, 1, 0, '', ('1.2.3.4', 0)), (2, 2, 0, '', ('1.2.3.4', 0))]

etc.  if you're behind a firewall/NAT etc and you want your "public IP",
you can do something like:

    >>> import re, urllib
    >>> ip = urllib.urlopen('http://checkip.dyndns.org').read()
    >>> re.search("(\d+\.\d+\.\d+.\d+)", ip).group()
    '4.3.2.1'

hope this helps!

</F>






More information about the Python-list mailing list