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! :-)

3 comments:

Ataru Atlanta said...

You can do better for fixhosts.sh:

#!/bin/sh

file=/etc/hosts
interface=eth0

ip=`ifconfig $interface | grep "inet addr" | sed 's/^.*inet\ addr:\([0-9]*.[0-9]*.[0-9]*.[0-9]*\).*$/\1/'`
hostname=`hostname`

if [ `grep -c $hostname $file` = 0 ] ; then
echo $ip $hostname >> $file
else
cat $file | sed s/^.*$hostname.*$/$ip\ $hostname/ > /tmp/.fixed
mv /tmp/.fixed $file
fi

HelenaÅÖ said...

Thanks Shihab! This was just what I was looking for.

sketchy00 said...

Correct me if I'm wrong, but does this leave the hosts file in a correctly formed state? After I run the script, I see /etc/hosts displays:

127.0.0.1 localhost
192.168.0.50 workstation1

Shouldn't there be an FQDN included in the line before the simple computer name? ...such as:

127.0.0.1 localhost
192.168.0.50 workstation1.mydomain.org workstation 1

How can the script be adjusted to accomodate this?