Last active
October 3, 2020 21:39
-
-
Save chrisstaite/478c108a856015d820d955993cdec635 to your computer and use it in GitHub Desktop.
Update /etc/hosts with IPv6 addresses given their IPv4 hostname
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
zeroize_macaddrs () | |
{ | |
sed -e 's/\(\s\)\([0-9a-f]\):/\10\2:/' -e 's/\([^0-9a-f]\)\([0-9a-f]\):/\10\2:/g' -e 's/:\([0-9a-f]\)$/:0\1/' | |
} | |
find_ip4 () | |
{ | |
grep 'on-dhcp-event' /etc/hosts | zeroize_macaddrs | grep "$1" | while read ip dns _ mac ; do | |
if ! echo "$ip" | grep "." > /dev/null ; then | |
continue | |
fi | |
if [ "$1" = "$mac" ]; then | |
echo "$dns" | |
return | |
fi | |
done | |
} | |
find_ip6 () | |
{ | |
foundip="" | |
grep 'ip6-neigh' /etc/hosts | { while read ip _ _ mac ; do | |
if ! echo "$ip" | grep ":" > /dev/null ; then | |
continue | |
fi | |
if [ "$1" = "$mac" ]; then | |
foundip="$ip" | |
fi | |
done | |
echo "$foundip"; } | |
} | |
update_hosts() | |
{ | |
change="0" | |
ip -6 neigh list nud reachable | grep -v "^fe80" | while read addr _ _ _ mac _ ; do | |
existing=$(find_ip6 "$mac") | |
if [ "$existing" = "$addr" ]; then | |
# Already in the hosts file | |
continue | |
fi | |
if ! [ -z "$existing" ]; then | |
# Already in the hosts file with a different address, remove it | |
sed -zi 's/^$existing.*$//' /etc/hosts | |
fi | |
name=$(find_ip4 "$mac") | |
if ! [ -z "$name" ]; then | |
# Add to the hosts file | |
echo -e "$addr\t$name\t#ip6-neigh $mac" >> /etc/hosts | |
change="1" | |
fi | |
done | |
if [ "$change" = "1" ]; then | |
killall -HUP dnsmasq | |
fi | |
} | |
main() | |
{ | |
while true; do | |
update_hosts | |
sleep 60 | |
done | |
} | |
main & |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment