码迷,mamicode.com
首页 > 其他好文 > 详细

获取本机网卡ip地址

时间:2018-01-24 12:29:31      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:wlan0   code   col   imp   ifreq   main   pack   inet_ntoa   ioctl   

import sys, os
import socket, struct, fcntl
import six
import psutil


def get_ip(iface="enp0s3"):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sockfd = sock.fileno()
    SIOCGIFADDR = 0x8915

    if six.PY3:
        ifreq = struct.pack(‘16sH14s‘, iface.encode(encoding="utf-8"), socket.AF_INET,
                            (‘\x00‘ * 14).encode(encoding="utf-8"))
    else:
        ifreq = struct.pack(‘16sH14s‘, iface, socket.AF_INET, b‘\x00‘ * 14)

    try:
        res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
    except Exception as e:
        return
    ip = struct.unpack(‘16sH2x4s8x‘, res)[2]
    return socket.inet_ntoa(ip)


def main():
    network_list = psutil.net_io_counters(pernic=True)
    for net_name in network_list:
        interfaces = [
            "eth0",
            "eth1",
            "eth2",
            "wlan0",
            "wlan1",
            "wifi0",
            "ath0",
            "ath1",
            "ppp0",
            "enp0s3",
            "bond0"
        ]
        if net_name in interfaces:
            ip = get_ip()
            if ip:
                print(net_name, ip)


if __name__ == "__main__":
    main()

获取本机网卡ip地址

标签:wlan0   code   col   imp   ifreq   main   pack   inet_ntoa   ioctl   

原文地址:https://www.cnblogs.com/lmx1002/p/8340857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!