python 获取linux 本机IP地址

来源:互联网 发布:mac系统移动硬盘格式 编辑:程序博客网 时间:2024/06/05 06:24
#!/usr/bin/env python#coding: utf-8import psutilimport socketimport structimport fcntldef getip(ethname):    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0X8915, struct.pack('256s', ethname[:15]))[20:24])ipList = {}ditNet = psutil.network_io_counters(pernic=True)for strNet in ditNet.keys():    ipList[strNet] = getip(strNet)print(ipList)


需要先安装psutil模块

输出结果:{'lo': '127.0.0.1', 'eth0': '192.168.1.205'}


原创粉丝点击