How does /etc/hosts or /private/etc/hosts work on 10.11

Networkunix

I've been trying to test my knowledge of what /etc/hosts is but I'm not getting anywhere. From understanding the point of /etc/hosts is it can round host names to ip addresses. So if you put the following in your /etc/hosts file:

127.0.0.1:3000 foo

then a curl foo should send a GET request to the local host on port 3000. However there is a wrinkle, because aparently on OSX 10.11.6 it doesn't use /etc/hosts instead it uses /private/etc/hosts, so then adding the above line to that file should work. But it doesn't because there is a further wrinkle, you have to reset the DNS cache, which according to this site can be done with the following command: sudo killall -HUP mDNSResponder. Am I missing something here?

When I curl localhost:3000 I get the rails hello world blog (because I have the default rails hello world blog running)

➜ curl localhost:3000
.
.
.
<strong>Rails version:</strong> 5.0.0.1<br />
<strong>Ruby version:</strong> 2.3.1 (x86_64-darwin15)
</p>
</section>
</div>
</body>
</html>
➜

however when I try to curl the custom domain name it doesn't work:

➜ sudo vim /private/etc/hosts
➜ sudo killall -HUP mDNSResponder
➜ cat /private/etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
127.0.0.1:3000 foo
255.255.255.255 broadcasthost
::1             localhost
➜ curl foo
curl: (6) Could not resolve host: foo

What am I doing wrong here?

Thanks 🙂

Best Answer

The /etc/hosts file on UNIX systems is for local DNS resolving.

As such, it doesn't take into account ports - it links hostnames with IP addresses, like the Domain Name Service.

Adding the following line:

127.0.0.1 foo

to your /etc/hosts file tells the internal DNS responder to send requests for foo to 127.0.0.1.

It will allow you to do the following:

# curl foo:3000