views:

309

answers:

4

Is there a way to programmatically add hosts to the local name resolver under Linux?

I would rather avoid fiddling with /etc/hosts dynamically...

Example: add the name foo and bind it to the local port 127.1.2.3

Use Case: I have an application installed locally accessible through a web browser. I'd like the application to be accessible through a local URI.

A: 

The google search term you want is "DDNS" for "Dynamic DNS". That's a technology for dynamically adding records to DNS servers, which sounds like exactly what you want. I'm pretty sure the bind in most lunix distros supports it, but you may need to read up on how to configure it.

Berry
+1  A: 

If you'll only add hosts, a pretty safe way to do it is

echo -e "ip.add.re.ss\thostname" >> /etc/hosts

Now, if you want to remove them it starts getting hairy. I suspect you also want to remove them.

If this is the case you can use Dynamic DNS, for example, BIND has the nsupdate tool to update zone files:

       $ nsupdate
       > update delete oldhost.example.com A
       > update add newhost.example.com 86400 A 172.16.1.1
       > send

This does the following:

Any A records for oldhost.example.com are deleted. And an A record for newhost.example.com with IP address 172.16.1.1 is added. The newly-added record has a 1 day TTL (86400 seconds).

Vinko Vrsalovic
Could I be binding the name "foo" to the local address 127.0.0.1 on port 9999 for example?
jldupont
DNS maps IP addresses to names, ports are not part of IP addresses. So, no.
Vinko Vrsalovic
@vinko: forgot that little detail... you are so right.
jldupont
@vinko: How do you get nsupdate to only update the *local dns cache* and not try to communicate with others name servers?
jldupont
You cannot: dynamic update updates a zone, not a cache. Updating the cache cannot be done by standard ways (each resolver may have its own proprietary way, which one do you use?)
bortzmeyer
@bortzmeyer: Is there another way? i.e is the local cache accessible another way?
jldupont
+4  A: 

add the name foo and bind it to the local port 127.0.0.1:9999

What is it that you want? You can add foo 127.0.0.1 to hosts or do the equivalent in your nameserver, but a connection to foo on port 1234 will always go to 127.0.0.1:1234 -- it's not possible to redirect that to port 9999 based on name, which is lost by the time connect is called.

On Linux you can add IPs to the loopback device (i.e. ip addr add 127.1.2.3 dev lo), and then use iptables to change all connections destined for 127.1.2.3:1234 to instead go to 127.0.0.1:9999, but I can't tell from your question if that the observable behavior you want.

ephemient
A: 

I'll be going with a recent discovery: multicast-dns using the Avahi package. An example can be found here.

jldupont