This question already has an answer here:
- Getting MAC Address 13 answers
The goal is to collect the MAC address of the connected local NIC, not a list of all local NICs :)
By using socket
and connect (to_a_website)
,
I can just use getsockname()
to get the IP,
that is being used to connect to the Internet.
But from the IP how can I then get the MAC address of the local NIC ?
Main reason for the question is if there are multiple NICs.
Use netifaces module. It's also on PyPI so you can install it via
easy_install
orpip
.You cannot retrieve the MAC address of an external IP.
See the discussions over at how to get mac address of external IP in C# for more clarification.
As vartec suggested
netifaces
should work well to go from IP->iface:Testing:
Another roundabout way to get a systems mac id is to use the ping command to ping the system's name then performing an arp -a request against the ip address that was pinged. the downfall to doing it that way thou is you need to write the ping response into the memory of python and performing a readline operation to retrieve the ip address and then writing the corresponding arp data into memory while writing the system name, ip address, and mac id to the machine in question to either the display or to a test file.
Im trying to do something similar as a system verification check to improve the automation of a test procedure and the script is in python for the time being.
A primitive way of doing this would be to use the commandline tools available on your OS. Run the tool using the
subprocess
module (notos.system()
!), collect the output, and parse it.On Windows, the command you want is
ipconfig /all
.On most Unices, including Linux, OSX and BSD, it's
ifconfig
.There may be a better way of doing this without shelling out to a command-line utility, but I don't know it... yet.
Example output of
ipconfig /all
on Windows XP:Output of
ifconfig
under Linux:You Cannot catch the mac address from a socket.your need an ethernet frame, which can be found at the lowest layer of tcp processing chain.to do that you need to monitor(capture) your network traffic, find some packets by parsing the packet's header. and extract the required information such as mac address from it.
this is useful code span , that can help you to do that.