M99
M99

Reputation: 1907

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.

Upvotes: 12

Views: 39335

Answers (7)

Marcelo Vinicius
Marcelo Vinicius

Reputation: 863

You can do this just unique command bellow:

sudo sh -c -e "echo '$(hostname -I | awk '{print $1}') youhostname.local' >> /etc/hosts"

Upvotes: 0

Markus Pscheidt
Markus Pscheidt

Reputation: 7331

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

Upvotes: 7

Tsioneb
Tsioneb

Reputation: 1

I personally use this script to set my hostname (existing one) + dynamic IP to /etc/hosts file :

#!/bin/bash
ipaddr=$(/sbin/ifconfig eth0| grep 'inet addr' | cut -d: -f2 | awk '{print $1}')
hn=$(hostname)
hnd=$(hostname -f)
sed -i '2s/.*/'$ipaddr'  '$hnd'   '$hn'/' /etc/hosts

Kind regards,

Upvotes: 0

nomadic_squirrel
nomadic_squirrel

Reputation: 644

I took what @Markus did and put it into a normal script. This works on my Fedora 20 box:

#!/bin/sh

MYHOST=firtree

echo "before:"
cat /etc/hosts

# Remove current line with hostname at the end of line ($ means end of line)
sed -i '/'$MYHOST'$/ d' /etc/hosts

echo "after remove: "
cat /etc/hosts

IPADDR=$(ifconfig | awk -F" +|:" '/inet addr/ && $4 != "127.0.0.1" {print $4}')
echo "$IPADDR $MYHOST" >>/etc/hosts

echo "ip: " $IPADDR
echo "final: "
cat /etc/hosts

This does have to be run as root, and probably should go in an init.d folder.

Upvotes: 1

deepujain
deepujain

Reputation: 687

From

ipaddr=$(ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}’)
host=`hostname`
fhost=`hostname -f`

echo "$ipaddr $fhost $host" >> /etc/hosts

cat /etc/hosts

Upvotes: 0

Diego Torres Milano
Diego Torres Milano

Reputation: 69189

Use avahi (which should be on your distro repositories), then you can

$ ping youhostname.local

Upvotes: 1

Marc B
Marc B

Reputation: 360562

dhcpcd has a -c/--script option to run an external script anytime it configures or brings up an interface. You can use this to manually update the hosts file with the configured hostname.

Upvotes: 5

Related Questions