获取本机网卡ip地址

Posted 悟-空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取本机网卡ip地址相关的知识,希望对你有一定的参考价值。

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地址的主要内容,如果未能解决你的问题,请参考以下文章

Java获取本机的ip地址

Linux C语言 获取本机(所有网卡)IP地址(IPV4)

获取本机网卡ip地址

获取本机IP地址

MFC编程中如何获取本机网卡信息以及IP,DNS,网关等

如何查询Windows电脑网卡获取到的IP地址