Finding local IP addresses using Python's stdlib

后端 未结 30 3076
北恋
北恋 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条回答
  •  萌比男神i
    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. :)

提交回复
热议问题