pythonホストIPの取得
5496 ワード
# -*- coding=utf8 -*-
import socket
def get_local_ip():
host_ip = "1.1.1.1" # get ip by config
if not is_ipv4_address(host_ip):
try:
host_ip = get_host_ip_by_socket()
except Exception as err:
print("Get IP ERROR by socket method, err: %s" % err)
host_ip = "127.0.0.1"
return host_ip
def get_host_ip_by_socket():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
if is_ipv4_address(ip):
return ip
except Exception as err:
print("Through link to '8.8.8.8:80' get IP Error: %s" % err)
ip = socket.gethostbyname(socket.gethostname())
print("Get IP by host name: %s" % ip)
finally:
s.close()
return ip
def is_ipv4_address(string_ip):
"""
:rtype: bool
"""
try:
socket.inet_aton(string_ip)
except socket.error:
return False
return True
if __name__ == '__main__':
print get_local_ip()