查找局域网树莓派raspberry的mac地址和ip

依赖python库:

python 复制代码
pip install socket
pip install scapy

运行代码:

python 复制代码
import socket
from scapy.layers.l2 import ARP, Ether, srp


def get_hostname(ip_address):
    try:
        return socket.gethostbyaddr(ip_address)[0]
    except socket.herror:
        # 未能解析主机名
        return None


def scan_network(ip_range):
    """
    扫描指定 IP 范围内的局域网,返回找到的 IP 和 MAC 地址列表
    """
    arp_request = ARP(pdst=ip_range)
    broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = srp(arp_request_broadcast, timeout=1, verbose=False)[0]

    devices_list = []
    for sent, received in answered_list:
        hostname = get_hostname(received.psrc)
        devices_list.append({'ip': received.psrc, 'mac': received.hwsrc, 'hostname': hostname})
        print(f"IP: {received.psrc}, MAC: {received.hwsrc}, Hostname: {hostname}")  # DEBUG

    return devices_list


# 请替换成你的实际IP范围
network_devices = scan_network('192.168.1.1/24')

raspberry_pis = [device for device in network_devices if
                 device['hostname'] and 'raspberrypi' in device['hostname'].lower()]

for pi in raspberry_pis:
    print(f"Found Raspberry Pi! Hostname: {pi['hostname']}, IP: {pi['ip']}, MAC: {pi['mac']}")

以上代码的运行有个工具的依赖

  1. Npcap来源github
    Npcap来自官网

  2. Bonjour来自github(这个通常Windows会自带,如果没有就下载安装一下)

通常,上面这个代码可能无法正常显示raspberry的主机名,那就要结合ping -4 raspberrypi.local指令了,代码如下:

python 复制代码
import socket
from scapy.layers.l2 import ARP, Ether, srp
import subprocess


def get_hostname(ip_address):
    try:
        return socket.gethostbyaddr(ip_address)[0]
    except socket.herror:
        # 未能解析主机名
        return None


def ping_host(hostname):
    try:
        subprocess.check_output(['ping', '-4', hostname])
        return True
    except subprocess.CalledProcessError:
        return False


def get_ip_from_hostname(hostname):
    try:
        return socket.gethostbyname(hostname)
    except socket.error:
        return None


def scan_network(ip_range):
    """
    扫描指定 IP 范围内的局域网,返回找到的 IP 和 MAC 地址列表
    """
    arp_request = ARP(pdst=ip_range)
    broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    answered_list = srp(arp_request_broadcast, timeout=1, verbose=False)[0]

    devices_list = []
    for sent, received in answered_list:
        hostname = get_hostname(received.psrc)
        devices_list.append({'ip': received.psrc, 'mac': received.hwsrc, 'hostname': hostname})
        print(f"IP: {received.psrc}, MAC: {received.hwsrc}, Hostname: {hostname}")  # DEBUG

    return devices_list


def find_raspberry_pi(devices_list):
    raspberry_pi_hostname = 'raspberrypi.local'
    if ping_host(raspberry_pi_hostname):
        raspberry_pi_ip = get_ip_from_hostname(raspberry_pi_hostname)
        for device in devices_list:
            if device['ip'] == raspberry_pi_ip:
                return device
    return None


# 请替换成你的实际IP范围
network_devices = scan_network('192.168.1.1/24')
raspberry_pi = find_raspberry_pi(network_devices)

if raspberry_pi:
    print(
        f"Found Raspberry Pi! Hostname: {raspberry_pi['hostname']}, IP: {raspberry_pi['ip']}, MAC: {raspberry_pi['mac']}")
else:
    print("Raspberry Pi not found on the network.")

看看运行结果:

已经顺利找到了局域网树莓派的ip~

如果还有什么问题,欢迎留言~

相关推荐
德迅云安全-上官14 小时前
源站隐身 + 流量清洗,高防 IP 品牌实力精选
网络·网络协议·tcp/ip
Ai拆代码的曹操21 小时前
TCP RST 包全链路定位:从 Connection Reset 错误到 Nginx keepalive_timeout 不匹配
网络协议·tcp/ip·nginx
瓦学妹1 天前
代理IP连接失败怎么办?2026代理IP异常排查与解决方法
网络·网络协议·tcp/ip
ITxiaobing20231 天前
广告归因数据对齐实战:从IP溯源看点击欺诈与AppsFlyer P360的匹配度优化
大数据·网络协议·tcp/ip
儒雅的烤地瓜1 天前
计算机网络 | 网络诊断双刃剑:Tracert路由追踪实战与Windows防火墙端口配置指南
tcp/ip·计算机网络·wireshark·防火墙·powershell·cmd
budaoweng06091 天前
charles报错HTTP/1.1 200 Connection established
网络·网络协议·http
用户3169353811831 天前
Kea DHCPv4 + IPAM Hook 完整工作流程和Kea DHCPv6 + IPAM Hook 完整工作流程
tcp/ip
TlSfoward1 天前
爬虫指纹漂移监控与回归测试:JA3/JA4 变化为什么会影响线上验证 TLSFOWARD
数据库·爬虫·网络协议·搜索引擎
IPDEEP全球代理1 天前
住宅IP、移动IP、机房IP有什么区别?
网络·网络协议·tcp/ip
周洲08301 天前
STM32+ESP8266 WiFi 远程环境监测平台|本地 OLED 显示 + TCP 上传电脑 / 手机
stm32·tcp/ip·电脑