Finding local IP addresses using Python's stdlib

后端 未结 30 2644
北恋
北恋 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:21

    Variation on ninjagecko's answer. This should work on any LAN that allows UDP broadcast and doesn't require access to an address on the LAN or internet.

    import socket
    def getNetworkIp():
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.connect(('', 0))
        return s.getsockname()[0]
    
    print (getNetworkIp())
    

提交回复
热议问题