views:

2359

answers:

9

I'd like to search for a given MAC address on my network, all from within a Python script. I already have a map of all the active IP addresses in the network but I cannot figure out how to glean the MAC address. Any ideas?

A: 

I don't think there is a built in way to get it from Python itself.

My question is, how are you getting the IP information from your network?

To get it from your local machine you could parse ifconfig (unix) or ipconfig (windows) with little difficulty.

Benjamin W. Smith
+5  A: 

You need ARP. Python's standard library doesn't include any code for that, so you either need to call an external program (your OS may have an 'arp' utility) or you need to build the packets yourself (possibly with a tool like Scapy.

Allen
A: 

Depends on your platform. If you're using *nix, you can use the 'arp' command to look up the mac address for a given IP (assuming IPv4) address. If that doesn't work, you could ping the address and then look, or if you have access to the raw network (using BPF or some other mechanism), you could send your own ARP packets (but that is probably overkill).

nsayer
+1  A: 

If you want a pure Python solution, you can take a look at Scapy to craft packets (you need to send ARP request, and inspect replies). Or if you don't mind invoking external program, you can use arping (on Un*x systems, I don't know of a Windows equivalent).

Sylvain Defresne
A: 

It seems that there is not a native way of doing this with Python. Your best bet would be to parse the output of "ipconfig /all" on Windows, or "ifconfig" on Linux. Consider using os.popen() with some regexps.

Martin Cote
A: 

You would want to parse the output of 'arp', but the kernel ARP cache will only contain those IP address(es) if those hosts have communicated with the host where the Python script is running.

ifconfig can be used to display the MAC addresses of local interfaces, but not those on the LAN.

EmmEff
A: 

Mark Pilgrim describes how to do this on Windows for the current machine with the Netbios module here. You can get the Netbios module as part of the Win32 package available at python.org. Unfortunately at the moment I cannot find the docs on the module.

Joe Skora
A: 

as python was not meant to deal with OS-specific issues (it's supposed to be interpreted and cross platform), I would execute an external command to do so:

in unix the command is ifconfig

if you execute it as a pipe you get the desired result:

import os;
myPipe=os.popen2("/sbin/ifconfig","a");
print(myPipe[1].read());
kiwi
Python has OS-specific modules, so I think you answer is misleading. The pythonic way to handle this would be a module to have an OS independent interface that could be sub classed by OS specific plugins.
Walter
+2  A: 

This article, "Send hand-crafted Ethernet Frames in Python (ARP for example)", seems to be exactly what you are looking for.

alif