#!/bin/sh

# Example Request:
# http://192.168.1.1/tools/ipaddr.html?format=json
#
# result:
# { "mac_address" : "11-22-33-44-55-66", "ip_address" : 192.168.1.101" }

IP="${1:-$REMOTE_ADDR}"		# e.g. '192.168.1.101' or '2a02:810a:8e80:1564:3681:c4ff:feee:68be'

http_header()
{
	local mime="${1:-text/plain}"

	echo -en "Content-type: ${mime}\n\n"
}

output_json_mac_and_ip()
{
	local mac="$1"
	local ip="$2"

	cat <<EOF
{ "mac_address" : "$mac", "ip_address" : $ip" }"
EOF
}

ipv4_to_mac()
{
	local ip="$1"
	local line mac

	# format of /proc/net/arp (IPv4n only) is like:
	# 10.63.196.161  0x1  0x6  00:10:75:2d:80:e1  *  eth0.1
	while read line; do {
		set -- $line

		case "$1" in
			"$ip")
				mac="$4"
				echo "$mac"
				return 0
			;;
		esac
	} done <'/proc/net/arp'

	# can fail if e.g.
	# - client is IPv6
	# - client not linklocal
	# - client is a local interface (e.g. NATed)

	return 1
}

http_header 'application/json'

if MAC="$( ipv4_to_mac "$IP" )"; then
	output_json_mac_and_ip "$MAC" "$IP"
else
	output_json_mac_and_ip 'null' "$IP"
fi
