ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/ns_dev/Python/NinoCode/Active_prgs/MacAddrGetter.py
Revision: 8
Committed: Sat May 5 04:21:19 2012 UTC (13 years, 10 months ago) by ninoborges
Content type: text/x-python
File size: 1590 byte(s)
Log Message:
Initial Import

File Contents

# User Rev Content
1 ninoborges 8 ## This program will return the mac address of a remote machine on Win
2     ## EBorges
3    
4     #!/usr/bin/env python
5    
6     import ctypes
7     import socket
8     import struct
9    
10     def get_macaddress(host):
11     """ Returns the MAC address of a network host, requires >= WIN2K. """
12    
13     # Check for api availability
14     try:
15     SendARP = ctypes.windll.Iphlpapi.SendARP
16     except:
17     raise NotImplementedError('Usage only on Windows 2000 and above')
18    
19     # Doesn't work with loopbacks, but let's try and help.
20     if host == '127.0.0.1' or host.lower() == 'localhost':
21     host = socket.gethostname()
22    
23     # gethostbyname blocks, so use it wisely.
24     try:
25     inetaddr = ctypes.windll.wsock32.inet_addr(host)
26     if inetaddr == 0 or -1:
27     raise Exception
28     except:
29     hostip = socket.gethostbyname(host)
30     inetaddr = ctypes.windll.wsock32.inet_addr(hostip)
31    
32     buffer = ctypes.c_buffer(6)
33     addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
34     if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:
35     raise WindowsError('Retreival of mac address(%s) - failed' % host)
36    
37     # Convert binary data into a string.
38     macaddr = ''
39     for intval in struct.unpack('BBBBBB', buffer):
40     if intval > 15:
41     replacestr = '0x'
42     else:
43     replacestr = 'x'
44     macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])
45    
46     return macaddr.upper()
47    
48     if __name__ == '__main__':
49     print 'Your mac address is %s' % get_macaddress('localhost')
50