Get Server IP address from JSP Request/session object

后端 未结 5 661
悲哀的现实
悲哀的现实 2020-12-18 03:15

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?

5条回答
  •  情歌与酒
    2020-12-18 04:17

    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();
                }
                %>
                
  • InetAddress: <%=serverAddress %>
  • InetAddress.hostname: <%=hostname %>
提交回复
热议问题