获取客户端的IP地址

编程入门 行业动态 更新时间:2024-10-15 22:27:12
本文介绍了获取客户端的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.

以下是我目前的代码:

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

路2

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-For" 并依赖于 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 en.wikipedia/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地址

本文发布于:2023-11-25 23:44:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631817.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   地址   IP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!