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.