树莓派使用python3获取网卡IP地址

作者: 管理员 分类: 源码展示,设备趣玩 发布时间: 2020-10-17 20:24

今天捣鼓树莓派遇到到问题,用Python3获得本地IP地址,首先想到用socket.gethostbyname,不废话,直接上代码!

import socket
import fcntl
import struct
def get_ip_address(ethname):
    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,
        struct.pack(b'256s',b'wlan0')
    )[20:24])
print get_ip_address("lo")
print get_ip_address("eth0")
print get_ip_address("wlan0")

发表评论

电子邮件地址不会被公开。