python 获取linux IP地址


获取Linux上IP地址

linux命令

ifconfig

python程序

import socket

def get_host()
	hostname = socket.gethostname()
    ip = socket.gethostbyname(hostname)
	
	return ip

python程序指定网口

def get_host()
	ifname = "eth0"  # 指定网口
	
    import fcntl, struct, socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
   
    ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', bytes(ifname,encoding="utf8")))[20:24])
    
    return ip

注意:

  • struct.pack(str,bytes) ,后面为bytes类型