def get_all_ips():
""" try to get all IPs of this machine
The resulting list of IPs contains non-local IPs first, followed by
local IPs (starting with "127....").
"""
def get_ips_of_name(name):
try:
ips = socket.gethostbyname_ex(name)
if len(ips) == 3:
return ips[2]
except socket.gaierror:
return []
result = []
result.extend(get_ips_of_name(socket.gethostname()))
result.extend(get_ips_of_name("localhost"))
filtered_result = []
for one_ip in result:
if one_ip not in filtered_result:
filtered_result.append(one_ip)
# non-local IPs first
filtered_result.sort(key=lambda ip: ((1 if ip.startswith("127.") else 0), ip))
return filtered_result
评论列表
文章目录