Get hostname from request
Asked Answered
N

3

5

I'm running my application on Windows Server 2008 on an Intranet.

To login the application tries to get the hostname from the request to validate the user. However, sometimes the application returns the IP address instead of the name and some time later, without doing anything the application is able to resolve the name and everything works fine...

This is the code I'm using to get the hostname:

InetAddress inaHost = InetAddress.getByName(request.getRemoteAddr());
String hostname = inaHost.getHostName();
System.out.println("[[ Hostname = " + hostname + " ]]");

Is this because of the Intranet configuration (DNS!?), or is something wrong with my code, or witchcraft or something?

Negative answered 8/11, 2013 at 15:28 Comment(2)
Why all this reflection?Eckman
Sorry about the reflection. It was some "leftover" code from another approach I was trying. My bad.Negative
A
6

First try

System.out.println("Host = " + request.getServerName());
System.out.println("Port = " + request.getServerPort());

if doesnt work

hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
  while (interfaces.hasMoreElements()) {
    NetworkInterface nic = interfaces.nextElement();
    Enumeration<InetAddress> addresses = nic.getInetAddresses();
    while (hostName == null && addresses.hasMoreElements()) {
      InetAddress address = addresses.nextElement();
      if (!address.isLoopbackAddress()) {
        hostName = address.getHostName();
      }
    }
  }
}
Allie answered 8/11, 2013 at 15:35 Comment(6)
Unfornately, neither approach worked. The first one returned the IP address and the second one returned the hostname from where my application is running. Perhaps I didn't explain myself well. What I would like is to get the name of the remote users machine.Negative
can you try request.getRemoteHost()Allie
returned the IP as well. but what I would really like to know is why my code works the way I want 95% of the time, and the other 5% only the IP address is returnedNegative
Please see my answer why it happensAllie
Finally i got solution to your question just try the code snippetAllie
This code still gets the server's own hostname(s). Your other answers ditto. Don't answer multiple times, please delete.Thread
S
3

You will need to use the following function to get the remote address/hostname:

request.getRemoteHost();
Schipperke answered 30/4, 2016 at 3:59 Comment(0)
S
0

sometimes the application returns the IP address instead of the name

As referenced from this SO answer:

The issue could be since request.getRemoteHost() does a reverse DNS lookup instead of taking it from the HTTP headers; if it fails to look up the DNS information using the IP, it returns the IP address as a String.

Simonsimona answered 20/1, 2020 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.