Java 从 JSP 请求/会话对象获取服务器 IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3177203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:06:08  来源:igfitidea点击:

Get Server IP address from JSP Request/session object

javajsprequestip-addressresponse

提问by Don Ch

How can I get the IP address of the server from a JSP page?

如何从 JSP 页面获取服务器的 IP 地址?

Right now, all I can do is request.getLocalName(), which returns the server name, not the IP address?

现在,我所能做的就是 request.getLocalName(),它返回服务器名称,而不是 IP 地址?

采纳答案by ig0774

Actually, for the IP address of the server, you need to use

实际上,对于服务器的IP地址,您需要使用

String serverIP = request.getLocalAddr();

回答by Abhijeet Pathak

String sIPAddr = request.getRemoteAddr();

回答by Aaron Saunders

String addr = request.getRemoteAddr();

回答by Satish Sharma

request.getHeader("X_FORWARDED_FOR") 

回答by Nux

To get an actual server IP and hostname (actual and not set by e.g. a proxy) use this:

要获取实际的服务器 IP 和主机名(实际的而不是由例如代理设置的),请使用以下命令:

            <%@ page import="java.net.*" %> 
            [...]
            <%
            String hostname, serverAddress;
            hostname = "error";
            serverAddress = "error";
            try {
                InetAddress inetAddress;
                inetAddress = InetAddress.getLocalHost();
                hostname = inetAddress.getHostName();
                serverAddress = inetAddress.toString();
            } catch (UnknownHostException e) {

                e.printStackTrace();
            }
            %>
            <li>InetAddress: <%=serverAddress %>
            <li>InetAddress.hostname: <%=hostname %>