简体   繁体   English

从 Python 中的已知 MAC 地址获取本地 IP 地址?

[英]Get local IP Address from a known MAC Address in Python?

I am running a Python Script on the Raspberry Pi in order to get measured data out of a Smart Plug.我在 Raspberry Pi 上运行 Python 脚本,以便从智能插头中获取测量数据。 In my script I need to write the IP-Address of the Smart Plug so that I can retrieve the data it was measured.在我的脚本中,我需要编写智能插头的 IP 地址,以便检索它测量的数据。 The problem is that I need to be able to take the Smart Plug to different places without having to hard code its new local IP-Address every time.问题是我需要能够将智能插头带到不同的地方,而不必每次都对其新的本地 IP 地址进行硬编码。

I have the MAC Address so I am hoping there is an "easy" way to add a couple lines of code and retrieve the local IP-Address from the MAC (?) in the Python Script.我有 MAC 地址,所以我希望有一种“简单”的方法来添加几行代码并从 Python 脚本中的 MAC(?)检索本地 IP 地址。 Thanks!谢谢!

What you're describing can be accomplished by crafting an ARP packet to get that info .您所描述的可以通过制作一个 ARP 数据包来获取该信息来完成。

Generally something like:通常是这样的:

from scapy.all import srp, Ether, ARP ans,unans=srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168.1.0/24"),timeout=2)

ip = pkt[ARP].psrc

Sorry, I don't have enough rep to comment. 对不起,我没有足够的代表发表评论。 You may want to check for duplicates, I have answered the same question few days back. 您可能想检查重复项,几天前我回答了同样的问题。

Solution

This can be achieve using arp command in the subprocess module.这可以在子进程模块中使用 arp 命令来实现。 Here is code.这是代码。 Checked in windows.签入窗口。

import subprocess
cmd = 'arp -a | findstr "ff-ff-ff-ff-ff-ff" '
returned_output = subprocess.check_output((cmd),shell=True,stderr=subprocess.STDOUT)
print(returned_output)
parse=str(returned_output).split(' ',1)
ip=parse[1].split(' ')
print(ip[1])

The local ip address is not based on the MAC address.本地 IP 地址不是基于 MAC 地址的。 The router uses DHCP to give the devises an ip address.路由器使用 DHCP 为设备提供 IP 地址。 So there is no way to tell the router which IP he must give you other than changing the settings.所以除了更改设置之外,没有办法告诉路由器他必须给你哪个IP。

I would rather try to broadcast the ip and on the raspberry listen on the broadcast channel for the message you are looking for.我宁愿尝试广播 ip 并在覆盆子上在广播频道上收听您正在寻找的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM