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

发布时间:2024年01月18日

依赖python库:

pip install socket
pip install scapy

运行代码:

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会自带,如果没有就下载安装一下)

文章来源:https://blog.csdn.net/weixin_46084533/article/details/135670189
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。