Updating /etc/hosts with your DHCP address
From Research Computing
I needed to define the DHCP address of my in /etc/hosts at bootup. Here's one way to accomplish this. In the file /etc/network/interfaces, I added the last line to call the script /etc/getipaddr, the script is invoked after if-up is called.
flengyel@BPNY251:~$ more /etc/network/interfaces
# /etc/network/interfaces -- configuration file for ifup(8), ifdown(8)
# The loopback interface
# automatically added when upgrading
auto lo eth0
iface lo inet loopback
# please do not modify the following line
pre-up /sbin/ifconfig eth0 up # line maintained by pppoeconf
iface eth0 inet dhcp
# set the ip address of this machine in /etc/hosts
post-up /etc/getipaddr
The script /etc/getipaddr is somewhat inelegant, but it does the job. It also produces console output during bootup.
flengyel@BPNY251:~$ more /etc/getipaddr
#!/bin/bash
IPADDR=`ifconfig eth0 | grep 146.96 | awk '{ print $2 }' | awk -F: '{ print $2 }'`
echo DHCP address $IPADDR modifying /etc/hosts
sed -e 's/.* BPNY251.acad.gc.cuny.edu BPNY251/'$IPADDR' BPNY251.acad.gc.cuny.edu BPNY251/' \
/etc/hosts > /etc/hosts.tmp
mv /etc/hosts.tmp /etc/hosts
