0

I need to be able to get the loopback interface from within my program. I'm writing a dns resolver, but I can't touch etc/hosts directly. For example, if someone throws me "localhost" I need to resolve to either "127.0.0.1" or "::1". It would be a bonus if I could also detect custom loopback interfaces that people set themselves, though not mandatory. Is there a way I could see if the loopback address is "127.0.0.1" or "::1".

Really specific question. Thanks in advance.

1 Answer 1

2

There are two separate issues here.

1) There is nothing particularly special about the names "localhost". The reason "localhost" works is because most properly-configured DNS zones include an explicit entry for "localhost". If an unqualified hostname is looked up, a DNS resolver automatically tries appending domains given in the "search" directory in /etc/resolv.conf. A typical host's /etc/resolv.conf file would contain

search example.com
nameserver 192.168.0.1
nameserver 192.168.1.1

As a result, an DNS lookup on "localhost" will have the local resolver try to resolve "localhost.example.com", and example.com's zone file will have an explicit entry

$ORIGIN example.com
@         IN      SOA     ns1.example.com.   ((the rest of the SOA record

...

localhost     A 127.0.0.1

2) Now, regarding the local network interface, it depends on the platform, which you did not specify. It's done differently on BSD and Linux, and I would expect a completely different way it's done on MS-Windows.

Presuming you are referring to Linux, the list of local network interfaces is returned by getifaddrs(3) - http://manpages.courier-mta.org/htmlman3/getifaddrs.3.html

Its flags struct member, as documented contains flags that come from the SIOCGIFFLAGS ioctl, as documented in netdevice(7) - http://manpages.courier-mta.org/htmlman7/netdevice.7.html

As documented, the IFF_LOOPBACK flag marks loopback interfaces, and you can get their IP address from the same structure.

However, as I pointed out, if all you're doing is writing a resolver, figuring out the loopback interfaces is completely out of scope for you. The site administrator specifies the IP addresses of the loopback interface in the zone file, and you should not be concerned about it.

Sign up to request clarification or add additional context in comments.

1 Comment

The platform is CentOS. So yeah, linux. As to the first point, yeah, this is a special case for testing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.