From a name to an address
You type a name like example.com, but the network needs an IP address. Turning one into the other is name resolution, and Linux tries two sources: the local file /etc/hosts first, then DNS servers (listed in /etc/resolv.conf). getent hosts NAME does a lookup the same way a program would:
cat /etc/hosts
getent hosts localhostIn the terminal
student@vulntech:~$ cat /etc/hosts 127.0.0.1 vulntech localhost ::1 vulntech localhost student@vulntech:~$ getent hosts localhost ::1 vulntech localhost
Adding a name in /etc/hosts
/etc/hosts maps names to addresses by hand — useful for naming machines on a small network. Each line is an address then the names for it. Add one, then look it up:
echo "127.0.0.1 myserver" | sudo tee -a /etc/hosts
getent hosts myserverIn the terminal
student@vulntech:~$ echo "127.0.0.1 myserver" | sudo tee -a /etc/hosts [sudo] password for student: 127.0.0.1 myserver student@vulntech:~$ getent hosts myserver 127.0.0.1 myserver
Asking a DNS server: dig
For names not in /etc/hosts, a DNS server answers. dig queries one directly; @SERVER picks which. Here a small DNS server is running on this machine that answers for shop.lab, and dig +short shows just the address it returns:
dig +short @127.0.0.1 shop.lab
nslookup shop.lab 127.0.0.1In the terminal
student@vulntech:~$ dig +short @127.0.0.1 shop.lab 10.20.30.40 student@vulntech:~$ nslookup shop.lab 127.0.0.1 Server: 127.0.0.1 Address: 127.0.0.1#53 Name: shop.lab Address: 10.20.30.40 ** server can't find shop.lab: REFUSED
Common mistake: Order matters:
/etc/hostswins over DNS. A stray line there can send a name to the wrong address and override what DNS says — a classic cause of “it works on my machine”.
Remember: Name resolution turns a name into an IP:
/etc/hostsfirst, then DNS (/etc/resolv.conf). Look up withgetent hosts NAME; query a DNS server directly withdig @SERVER NAME.