#!/usr/bin/python

import ipcalc,sys,re,os
from optparse import OptionParser

from inspect import getmembers
from pprint import pprint
from subprocess import Popen, PIPE
from socket import gethostbyaddr 


def checkArgs():
	parser = OptionParser()
	parser.add_option("-n", "--network", dest="network",
					  help="network to perform the lookup. Ex: 10.243.135.1/24")
	parser.add_option("-m", "--mac",
					  dest="mac", 
					  help="mac address to look for. Ex: 00:34:55:aa:f4:12")

	(options, args) = parser.parse_args()

	for attr, value in options.__dict__.iteritems():
		if value is None:
			print "All arguments are mandatory!"
			print "Type findIP -h to get some help"
			exit(1)
			
	try:
		ipcalc.Network(str(options.network))

	except ValueError:
		print "Invalid network"

	mac=options.mac.replace('-','')
	mac=mac.replace(':','')
	mac=mac.lower()
	if not re.match("^[0-9a-f]{12}$", mac):
		print "Invalid MAC address"
		exit(1)
			
	return options.network,mac

network,mac=checkArgs()

networkList=ipcalc.Network(network)
#print vars(a)
#print vars(a.ip)
#pprint(getmembers(networkList))
#print a.host_last()
#print a.info()
	
print "First host: " + str(networkList.host_first())
print "Last host: " + str(networkList.host_last())
print

for ip in ipcalc.Network(network):
	p = Popen(['/usr/sbin/arp','-n'], stdout=PIPE)

	output = p.stdout.read()
	output=output.replace(':','')
	for line in output.rsplit('\n'):
		if line.rfind(mac) > 0:
			print
			print "IP found: " + line.rsplit()[0]
			print "Name: " + gethostbyaddr(str(line.rsplit()[0]))[0]
			exit()
	
	
	if ip >= networkList.host_first() and ip <= networkList.host_last():
		ip=str(ip)
		sys.stdout.write("\rPinging " + ip + "         ")
		sys.stdout.flush()
		os.system('/bin/ping -w1 -c1 '+ ip + ' > /dev/null 2>&1')

print
print "IP not found."
print
