How to prevent from DNS spoofing in Java code which obtains a name of localhost

FORTIFY static scan has detected that this piece of our java code is vulnerable to DNS spoofing attack:

public String getLocalhostName(){
    try {
        return Inet4Address.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        return null;
    }
}

FORTIFY also gives these recommendations:

Recommendations:

You can increase confidence in a domain name lookup if you check to
make sure that the host’s forward and backward DNS entries match.
Attackers will not be able to spoof both the forward and the reverse
DNS entries without controlling the nameservers for the target domain.
This is not a foolproof approach however: attackers may be able to
convince the domain registrar to turn over the domain to a malicious
nameserver. Basing authentication on DNS entries is simply a risky
proposition.

My questions are:

  1. Is getting the local host name really vulnerable to such an attack ? I can’t imagine such a scenario.
  2. How to implement this check in practice (in this code snippet)?

Tkank you.

Go to Source
Author: krokodilko