如何从 Java 中的 HTTP 标头中检索 IP 地址 [英] How can I retrieve IP address from HTTP header in Java

查看:28
本文介绍了如何从 Java 中的 HTTP 标头中检索 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇是否有任何库已经处理过这种东西,或者我必须自己再做一次.所以,问题是我想从我服务器上的访问者 HTTP 标头请求中获取 IP 地址字段,并用 Java 完成整个事情?你能帮忙的话,我会很高兴.提前致谢.

I am curious if there is any library that handles already this kind of stuff, or I have to do it by myself once again. So, the thing is I want to get IP address field from the visitors HTTP header request on my server, and do the whole thing in Java? Any help would be nice. Thanks in advance.

推荐答案

使用 getHeader(String Name) 方法 javax.servlet.http.HttpServletRequest 对象来检索的值Remote_Addr 变量.这是示例代码:

Use the getHeader(String Name) method of the javax.servlet.http.HttpServletRequest object to retrieve the value of Remote_Addr variable. Here is the sample code:

String ipAddress = request.getHeader("Remote_Addr");

如果这段代码返回空字符串,那么使用这种方式:

If this code returns empty string, then use this way:

String ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");

if (ipAddress == null) {
    ipAddress = request.getRemoteAddr();
}

这篇关于如何从 Java 中的 HTTP 标头中检索 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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