views:

3811

answers:

7

The /etc/hosts file can be used to override dns definitions, i.e. to point an hostname to a different ip.

I want to use /etc/hosts to make an alias record, i.e.e to make my computer think that www.mysite.com does not point to a "hard coded" up but instead is synonym of mychangingip.myip.com.

Can it be done?

A: 

I don't think so, hosts file is not really an dns server alternative. Instead of trying to figure out how to install and configure bind dns, you might want to try out filebased SheerDNS. http://threading.2038bug.com/sheerdns/ (best lightweight dns server i found through freshmeat).

Francis Siefken
SheerDNS seems highly broken: it sends back illegal DNS packets when you put a resource record type it does not recognize, it does not handle (such as SPF), it does not recognize AAAA records, it does not reply to ANY requests, etc. It seems a student experiment, not more.
bortzmeyer
A: 

I looked into this recently, I could not find a real solution. However, you can get partially what you want by adding a search line to /etc/resolv.conf e.g.:

search myip.com

Then it will look for mychangingip.myip.com when trying to resolve mychangingip See also the man page for resolv.conf

amarillion
A: 

This shell script might do the trick for you, if you just need to have the up-to-date IP in your hosts file and don't like the overhead of a custom DNS setup. You could for example run it regularly as a cronjob.

#!/bin/bash
# Get the dynamic IP (dirty, I know)
IP=`host -t a mychangingip.myip.com | perl -nle '/((?:\d+\.?){4})/ && print $1' | head -n1`

# Update the hosts file
if test -n "$IP"; then
    grep -v www.thesite.com /etc/hosts > /tmp/hosts
    echo "$IP www.thesite.com" >> /tmp/hosts
    cp /tmp/hosts /etc/hosts
fi
Guðmundur H
A: 

There are service providers that will comfortably and reliably do this for you. A prominent example is dyndns.

innaM
+2  A: 

/etc/hosts cannot be used to produce hostname "aliases".

The hosts file produces the internal equivalent of A and PTR records from the DNS, i.e. mapping of hostname to IP address and vice-versa.

It cannot be used to produce the same effect as a CNAME record.

Alnitak
A: 

One note of caution is if you have an entry like this :

 127.0.0.1     dev.example.com

When you actually get the request within your application (in my case ASP.NET) it will actaully have resolved to 'localhost' so you cant do things like this :

if (Request.Url.Authority == "dev.example.com) {
   // ...
}

The alias is resolved to 'localhost'. i think this behavior works as if it were a CNAME

Simon_Weaver
+1  A: 

If you want to SSH to a server (with a dynamically changing DNS entry) then you can effectively add an "alias" by (in the file ~/.ssh/config) creating an entry:

Host myAlias HostName mychangingip.myip.com

Then you can "ssh myAlias" (there are other directives which may be of use, e.g. User, Port etc).

Patrick