Finding local IP addresses using Python's stdlib

后端 未结 30 2645
北恋
北恋 2020-11-21 23:54

How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?

30条回答
  •  时光取名叫无心
    2020-11-22 00:38

    A version I do not believe that has been posted yet. I tested with python 2.7 on Ubuntu 12.04.

    Found this solution at : http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/

    import socket
    import fcntl
    import struct
    
    def get_ip_address(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15])
        )[20:24])
    

    Example Result:

    >>> get_ip_address('eth0')
    '38.113.228.130'
    

提交回复
热议问题