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类型
posted @ 2022-02-08 17:08  贝壳里的星海  阅读(762)  评论(0编辑  收藏  举报