【python】獲取linux主機ip的一種方法
阿新 • • 發佈:2019-02-08
python有好幾種方法可以獲取主機的ip地址。我常用的一種是通過socket.socket().inet_ntoa()來實現,非常方便;但這種方法有個限制就是要把網絡卡名(比如eth0)作為引數傳進來。所以加多了一個條件判斷,如果發現以上方法獲取ip拋異常時,那就用調起shell命令(ifconfig)和管道,把想要的ip給過濾出來。
import socket import fcntl import struct """ 獲取主機ip地址 引數ifname: 通過'lo'獲取的為環回地址, 通過'eth0'獲取的為主機ip地址 """ def get_ip_address(ifname='eth0'): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) except: ips = os.popen("LANG=C ifconfig | grep \"inet addr\" | grep -v \"127.0.0.1\" | awk -F \":\" '{print $2}' | awk '{print $1}'").readlines() if len(ips) > 0: return ips[0] return ''