Thursday, April 17, 2008

Update /etc/hosts with IP address assigned through DHCP

My /etc/hosts file looks something like:

127.0.0.1       localhost
127.0.1.1 shihabpc
The host name shihabpc should be mapped to my network's IP address; not to a loop back IP address like 127.0.1.1. This is some how mandatory for RMI to work properly.
But the problem is that I have used DHCP to assign IP address and that is changed from one boot to another. So I have to change the /etc/hosts file every time my IP address changes.
So, I have written a script to update /etc/hosts:
#!/bin/sh
# /home/shihab/fixhosts.sh

file=/etc/hosts
interface=eth0

ip=`ip addr show $interface`
ip=`echo "$ip" | grep "inet "`
ip=`echo "$ip" | cut -d "i" -f 2`
ip=`echo "$ip" | cut -d " " -f 2`
ip=`echo "$ip" | cut -d / -f 1`

hostname=`hostname`

found=0
while read line
do
if [ "`echo "$line" | grep $hostname`" != "" ]; then
line="$ip $hostname"
found=1
fi
if [ -z "$text" ]; then
text="$line"
else
text="$text\n$line"
fi
done < $file

if [ found = 0 ]; then
text="$text\n$ip $hostname"
fi

echo -e "$text" > $file
And added it as an init.d script:
#!/bin/sh
# /etc/init.d/fixhosts

case "$1" in
start)
/home/shihab/fixhosts.sh
;;
stop)
# do nothing ;)
;;
restart)
$0 stop
$0 start
;;
*)
echo "usage: $0 (start|stop|restart|help)"
esac
$sudo update-rc.d fixhosts defaults 99
That's it! :-)