Finding local IP addresses using Python's stdlib

后端 未结 30 2578
北恋
北恋 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
    慢半拍i (楼主)
    2020-11-22 00:20

    import socket
    socket.gethostbyname(socket.gethostname())
    

    This won't work always (returns 127.0.0.1 on machines having the hostname in /etc/hosts as 127.0.0.1), a paliative would be what gimel shows, use socket.getfqdn() instead. Of course your machine needs a resolvable hostname.

提交回复
热议问题