Finding local IP addresses using Python's stdlib

后端 未结 30 2574
北恋
北恋 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'
    
    0 讨论(0)
  • 2020-11-22 00:38

    If you're looking for an IPV4 address different from your localhost IP address 127.0.0.1, here is a neat piece of python codes:

    import subprocess
    address = subprocess.check_output(['hostname', '-s', '-I'])
    address = address.decode('utf-8') 
    address=address[:-1]
    

    Which can also be written in a single line:

    address = subprocess.check_output(['hostname', '-s', '-I']).decode('utf-8')[:-1]
    

    Even if you put localhost in /etc/hostname, the code will still give your local IP address.

    0 讨论(0)
  • 2020-11-22 00:40

    I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked.

    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    print(s.getsockname()[0])
    s.close()
    

    This assumes you have an internet access, and that there is no local proxy.

    0 讨论(0)
  • 2020-11-22 00:42

    On Linux:

    >>> import socket, struct, fcntl
    >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    >>> sockfd = sock.fileno()
    >>> SIOCGIFADDR = 0x8915
    >>>
    >>> def get_ip(iface = 'eth0'):
    ...     ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
    ...     try:
    ...         res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
    ...     except:
    ...         return None
    ...     ip = struct.unpack('16sH2x4s8x', res)[2]
    ...     return socket.inet_ntoa(ip)
    ... 
    >>> get_ip('eth0')
    '10.80.40.234'
    >>> 
    
    0 讨论(0)
  • 2020-11-22 00:44

    Note: This is not using the standard library, but quite simple.

    $ pip install pif

    from pif import get_public_ip
    get_public_ip()
    
    0 讨论(0)
  • 2020-11-22 00:46

    This method returns the "primary" IP on the local box (the one with a default route).

    • Does NOT need routable net access or any connection at all.
    • Works even if all interfaces are unplugged from the network.
    • Does NOT need or even try to get anywhere else.
    • Works with NAT, public, private, external, and internal IP's
    • Pure Python 2 (or 3) with no external dependencies.
    • Works on Linux, Windows, and OSX.

    Python 3 or 2:

    import socket
    def get_ip():
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            # doesn't even have to be reachable
            s.connect(('10.255.255.255', 1))
            IP = s.getsockname()[0]
        except Exception:
            IP = '127.0.0.1'
        finally:
            s.close()
        return IP
    

    This returns a single IP which is the primary (the one with a default route). If you need instead all IP's attached to all interfaces (including localhost, etc), see this answer.

    If you are behind a NAT firewall like your wifi box at home, then this will not show your public NAT IP, but instead your private IP on the local network which has a default route to your local WIFI router; getting your wifi router's external IP would either require running this on THAT box, or connecting to an external service such as whatismyip.com/whatismyipaddress.com that could reflect back the IP... but that is completely different from the original question. :)

    0 讨论(0)
提交回复
热议问题