Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding host name to /etc/hosts in Linux

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.

like image 358
M99 Avatar asked Feb 28 '11 16:02

M99


1 Answers

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
like image 77
Markus Pscheidt Avatar answered Sep 28 '22 12:09

Markus Pscheidt