-3

In my application I have written to find IP Address of user.

HttpServletRequest httpRequest = (HttpServletRequest) request;
String userIpAddress = httpRequest.getHeader("X-Forwarded-For");

        HttpServletRequest.getLocalAddr();

And getting the server ips can be done so:

Inet4Address.getLocalHost().getHostAddress();

So, If the user already logged in from one ip address, how to restrict his login from another ip address?

Vignesh Shiv
  • 1,129
  • 7
  • 22

3 Answers3

2

Try Following code:

Inet4Address address=(Inet4Address) Inet4Address.getLocalHost();
System.out.println(address.getHostAddress());

Inet4Address comes from java.net.Inet4Address;

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34
0

Best way to find host address in LAN can be done as follows:

System.out.println(InetAddress.getByName("anyhostname").getHostAddress());
Sachin Janani
  • 1,310
  • 1
  • 17
  • 33
0

Try this, it will enumerate all the interface's address of your local machine.

   try {
        Enumeration<NetworkInterface> interfaceEnumeration =
                NetworkInterface.getNetworkInterfaces();
        while (interfaceEnumeration.hasMoreElements()) {
            Enumeration<InetAddress> inetAddressEnumeration =
                    interfaceEnumeration.nextElement().getInetAddresses();
            while (inetAddressEnumeration.hasMoreElements()) {
                System.out.println(inetAddressEnumeration.nextElement().getHostAddress());
            }
        }
    } catch (SocketException e) {
        e.printStackTrace();
    }

But the following method is not reliable, in my testing environment, it always return the loop back interface address.

    try {
        InetAddress inetAddress[] = InetAddress.getAllByName("localhost");
        for (InetAddress address : inetAddress) {
            System.out.println(address.getHostAddress());
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
alijandro
  • 11,627
  • 2
  • 58
  • 74