1. 程式人生 > >Python小功能-獲取本機IP

Python小功能-獲取本機IP

socket start name finall close con def conn print

shell獲取IP太麻煩,python實現還是快點

獲取本機IP

1.方法一 第一種更好用,第二種會出現127.0.0.1的情況
import socket
def get_host_ip():
try:
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.connect((‘114.114.114.114‘,80))
ip=s.getsockname()[0]
finally:
s.close()
return ip

ip=get_host_ip()
print(ip)

  1. 方法二
    import socket
    hostname=socket.gethostname()
    ip=socket.gethostbyname(hostname)
    print(ip)

Python小功能-獲取本機IP