Obtain IP Address from MAC using python

北城以北 提交于 2019-12-02 05:01:42

问题


I have a device in my local network and know its MAC Address. It gets it's IP address automatically via DHCP. I want to obtain this IP.

I don't want to use nmap but scapy would be fine, as I'm importing from a kivy app.

I found:

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)

and with

ans.summary()

I get the following output:

Ether / ARP who has 192.168.43.1 says 192.168.43.92 ==> Ether / ARP is at 3e:f8:d9:45:1b:3d says 192.168.43.1

My two problems are:

1: I have to run the script with sudo python and I'm not sure about the permissons in kivy.

2: Is there a simple way to get the variables for IP/MAC out of the .summary()?


回答1:


Yes, you can do that using scapy. Here is an example of an ARP is-at packet:

###[ Ethernet ]###
  dst= 08:00:27:fa:25:8e
  src= 08:00:27:b1:af:68
  type= 0x806
    ###[ ARP ]###
     hwtype= 0x1
     ptype= 0x800
     hwlen= 6
     plen= 4
     op= is-at
     hwsrc= 08:00:27:b1:af:68
     psrc= 192.168.56.102
     hwdst= 08:00:27:fa:25:8e
     pdst= 192.168.56.101
        ###[ Padding ]###
            load= '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00'

You can assign the hwsrc and psrc values to a variable like this

srcMAC = pkt[ARP].hwsrc
srcIP = pkt[ARP].psrc

or just print them like this

print pkt[ARP].hwsrc
print pkt[ARP].psrc

Hope that helps.




回答2:


If the stucture of summary is always the same (what I assume), then you could import re and use a regex to extract the IP address.

Should be something like:

re.sub(r'.* says (.*) ==> Ether / ARP is.*', r'\1', ans.summary())

That works for me:

>>> import re
>>> x = "Ether / ARP who has 192.168.43.1 says 192.168.43.92 ==> Ether / ARP is at 3e:f8:d9:45:1b:3d says 192.168.43.1"
>>> re.sub(r'.* says (.*) ==> Ether / ARP is.*', r'\1', x)
'192.168.43.92'


来源:https://stackoverflow.com/questions/38182966/obtain-ip-address-from-mac-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!