Sometimes it is useful in bash scripts to resolve an IP address to a mac address. Here comes a simple script that perfroms this action:

#!/bin/bash
###############################################################################
#
# This script delivers the mac address for a  given IP address
#
# @usage getmacfromip IP_ADDRESS
# @author thorsten heymann <info@metashock.net>
# @params:
#
#	$1 => the ip address
#
###############################################################################
 
# ensure that we have root privileges. arp requires this
if [[ $EUID -ne 0 ]]; then
   echo "must be run as root"
   exit 1
fi
 
# get executable paths
ARP=`which arp`
CUT=`which cut`
GREP=`which grep`
PING=`which ping`
 
 
# ensure the ip address command line argument has been provided
if [ "$#" != "1" ] ; then
	echo "usage: $0 ip-address"
	exit 1
fi
 
# ping the machine once to be sure its mac is in the systems arp table
$PING $1 -c 1 -W 1 2>&1 > /dev/null
if [ "$?" != "0" ] ; then
	echo "no route to host"
	exit 1
fi
 
# get the mac address for host from arp table 
# Note! Sure, you can use arp -a IP but if mac was found arp returns 0. This is 
# not good for error handling. So we first pipe the whole arp table to grep ...
grepresult=`$ARP -a  | $GREP $1`
 
# ... now check the result code of grep. this should be 1 if nothing was found. 
# But since the machine was pinged before, and the ping was successfull this 
# should only by ping against local ip's (127.0.0.1, own IP) 
if [ "$?" != "0" ] ; then
	echo "IP not in arp table"
	exit 1
fi
 
# $grepresult contains a line like this: 
#	
#	server (192.168.0.1) at 00:15:17:45:4c:9c [ether] on eth2
#
# (@see man arp for mor details on arp -a's output)
#
# An easy way to extract the mac is to cut the line by whitespaces
# and simply use the fourth field ...
macaddress=`echo $grepresult | $CUT -d' ' -f4`
if [ "$?" != "0" ] ; then
	echo "error getting macaddress"
	exit 1
fi
 
# send the mac to stdout
echo $macaddress
 
# Another request serverd. Thanks and goodbye!
exit 0

Usage example:

user@host:~# ./getmacfromip 192.168.0.1
00:23:fe:e8:bd:49

Use it or modify it for your own needs.
Have fun!

Leave a Reply