思路是先获取网关,再拿到对应的IP信息,这样可以在没有公网是也能拿到地址:
import netifaces
def get_host_ip():
try:
gws = netifaces.gateways()
net_name = gws['default'][netifaces.AF_INET][1]
info = netifaces.ifaddresses(net_name)
ip = info[netifaces.AF_INET][0]['addr']
except:
ip = None
return ip
网友评论