獲取主機ip地址
阿新 • • 發佈:2021-12-08
import socket import commands def get_ip(): hostname = socket.gethostname() #print(hostname) hostip = "127.0.0.1" try: hostip = socket.gethostbyname(hostname) # 這個在linux 無法執行, 會走下面的cmd 來獲取ip , 但是在windows上這個命令執行,可以獲取地址 #print(hostip)return hostip except Exception,ex: # 這個ex 在windows 上會報錯 print(ex) if "127.0.0.1" in hostip or not hostip: try: cmd = "ifconfig|grep -v '127.0.0.1'|awk '{print $2}'|grep -oP '(\d+.\d+.\d+.\d+)'|head -1" (status,output)= commands.getstatusoutput(cmd) except Exception,ex: print(ex) return hostip if output and ' ' not in output: local_ip = output return local_ip return hostip hostip= get_ip() print(hostip)