Handy Python Snippets

Obtaining the local IP address (getip.py)

#!/usr/bin/env python

def getip():
 from socket import gethostbyaddr, gethostname
 theip = gethostbyaddr(gethostname())[2][0]
 return theip

Obtaining the local MAC address (getmac.py)

#!/usr/bin/env python

def getmac():
 import sys, os
 if sys.platform == 'win32':
  for line in os.popen("ipconfig /all"):
   if line.lstrip().startswith('Physical Address'):
    mac = line.split(':')[1].strip().replace('-',':')
  for line in os.popen("/sbin/ifconfig"):
   if line.find('Ether') > -1:
    mac = line.split()[4]
 return mac

Putting these together (test.py)

#!/usr/bin/env python
import getmac, getip

myip = getip.getip()
mymac = getmac.getmac()

print mymac + " has address: " + myip

Leave a Reply

Your email address will not be published. Required fields are marked *