获取客户端的IP地址 [英] Getting IP address of client

查看:349
本文介绍了获取客户端的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSP Servlets (容器: Glassfish )开发一个Web应用程序,我需要在其中获取客户端 IP地址

I am developing a web application using JSP, Servlets (Container: Glassfish) in which I need to get clients IP Address.

我获取客户端的IP地址,因为我想访问某些页面(如客户维护表单)只有在有办公室的电脑上,我想限制访问办公室以外的那些页面。

I am getting the clients IP address, because I want to give access to some pages (like Customer maintenance forms) only on computers withing the office, I want to restrict access to those pages outside office.

以下是我的代码到目前为止:

Following is my code so far:

String ipAddress =  request.getRemoteAddr();
System.out.println("IP Address: "+ipAddress);



way2



way2

String ipAddress=null;
String getWay = request.getHeader("VIA");   // Gateway
ipAddress = request.getHeader("X-FORWARDED-FOR");   // proxy
if(ipAddress==null)
{
    ipAddress = request.getRemoteAddr();
}
System.out.println("IP Address: "+ipAddress);

上面的代码给我不同的IP地址每个我重新启动计算机的时间(关机 - >开始或重新启动)。

Above code gives me different IP Address each time when I restart my computer (Shutdown->Start or Restart).

我收到 IP6 喜欢:

fe80:0:0:0:20ca:1776:f5ff:ff15%13

让我知道这段代码有什么问题?

Let me know what is wrong with this code?

推荐答案

正如@martin和这个答案所解释的那样,这很复杂。获取客户端的IP地址没有防弹方式。

As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.

您可以做的最好的事情是尝试解析X-Forwarded - 对于并依赖 request.getRemoteAddr();

The best that you can do is to try to parse "X-Forwarded-For" and rely on request.getRemoteAddr();

public static String getClientIpAddress(HttpServletRequest request) {
    String xForwardedForHeader = request.getHeader("X-Forwarded-For");
    if (xForwardedForHeader == null) {
        return request.getRemoteAddr();
    } else {
        // As of https://en.wikipedia.org/wiki/X-Forwarded-For
        // The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
        // we only want the client
        return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
    }
}

这篇关于获取客户端的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆