Is there an easy way to add DHCP issued IP address and host name of a Linux machine in /etc/hosts at system startup automatically?
Background:
My Linux machine has a host name in /etc/hostname and it won't resolve to anything when I ping. I manually added my host name and IP address in /etc/hosts for one my network related Java programs to work.
In Ubuntu, add an executable file into the /etc/network/if-up.d
directory. Files in this directory get executed after the network manager configures a network interface.
You may adapt the following script :
#!/bin/sh
set -e
if [ "$IFACE" = lo ]; then
exit 0
fi
myHostName=`hostname`
# Remove current line with hostname at the end of line ($ means end of line)
sed -i '/'$myHostName'$/ d' /etc/hosts
ipaddr=$(ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}')
echo "$ipaddr $myHostName" >>/etc/hosts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With