如何在servlet中获取客户端的远程地址?

77

有没有办法获取连接到服务器的客户端的原始IP地址?

我可以使用request.getRemoteAddr(),但我似乎总是得到代理或Web服务器的IP。

我想知道客户端用于连接到我的IP地址。有什么方法可以获取它吗?

12个回答

0
这是完整的解决方案,只需复制粘贴并运行代码。

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

@WebServlet("/ipaddress")
public class GetIpAddressServlet extends HttpServlet {
    
    /**
     * Author : Deepak Bajaj
     */

    public static final long serialVersionUID = 1L;

    // Below code is just to get the VALID IP Address headers
    public static final String[] VALID_IP_HEADER_CANDIDATES = { 
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR" };

    // To get the client's IP Address
    
    public static String GetIpAddressServlet(HttpServletRequest request) throws IOException, ServletException {
        
        for (String header : VALID_IP_HEADER_CANDIDATES) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            }
        }
        return request.getRemoteAddr();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get the client's IP address
        String clientIP = GetIpAddressServlet(request);

        // Print or use the client's IP address as needed
        System.out.println("Client IP Address: " + clientIP);

        // You can send the IP address as a response to the client if needed
        response.getWriter().write("Client IP Address: " + clientIP);
    }


注意:现在只需尝试通过远程客户端的机器访问您的应用程序http://IPofMachineWheretheCodeisHosted:PORT/ipaddress,您将获得远程客户端的IP地址。

-8
InetAddress inetAddress = InetAddress.getLocalHost();
String ip = inetAddress.getHostAddress();

这只是提供本地主机的IP地址。 - seenukarthi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接