1

I need to get 127.0.0.1 in Windows 'behind' corp DNS. The code I use is:

import java.net.InetAddress;

class IPAddressExample {
    public static void main(String args[]) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println("IP Address:- " + inetAddress.getHostAddress());
        System.out.println("Host Name:- " + inetAddress.getHostName());
    }
}

In Linux works and show me 127.0.0.1, but in Windows shows the IP Provided by DHCP. I need it because some test check that.

  • Can you confirm if it in fact shows the public IP address in Windows? – Sanil Khurana Oct 22 '19 at 04:12
  • 1
    https://stackoverflow.com/questions/9481865/getting-the-ip-address-of-the-current-machine-using-java – D V Santhosh Kiran Oct 22 '19 at 04:44
  • 1
    You already have 127.0.0.1. Why do you need to call an API to get a constant? – user207421 Oct 22 '19 at 04:47
  • 1
    if you need the loopback address use [getLoopbackAddress()](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/net/InetAddress.html#getLoopbackAddress()) and not `getLocalHost()` – user85421 Oct 22 '19 at 04:51
  • NB The Windows behaviour is correct here. Your Linux configuration is wrong, probably in `/etc/hosts`. The real hostname should map to the real LAN address, and `localhost` should map to 127.0.0.1. If you want the IP address corresponding to `localhost` and you aren't prepared to just use `127.0.0.1` (although in most places in Java you can use both interchangeably) you should proceed as per @R.Escalona's answer. – user207421 Oct 22 '19 at 06:38

1 Answers1

1

I tested on my Windows laptop with DHCP and I getting 127.0.0.1 with:

InetAddress.getByName("localhost").getHostAddress()