Get Server IP address from JSP Request/session obj

2019-01-26 14:20发布

问题:

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

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

回答1:

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

String serverIP = request.getLocalAddr();


回答2:

String sIPAddr = request.getRemoteAddr();


回答3:

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

            <%@ 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 %>


回答4:

String addr = request.getRemoteAddr();


回答5:

request.getHeader("X_FORWARDED_FOR")