jldupont
jldupont

Reputation: 96716

linux: adding hosts programmatically?

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.

Upvotes: 3

Views: 6358

Answers (4)

jldupont
jldupont

Reputation: 96716

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

Upvotes: 0

ephemient
ephemient

Reputation: 204718

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.

Upvotes: 4

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340231

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).

Upvotes: 1

Berry
Berry

Reputation: 1739

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.

Upvotes: 1

Related Questions