How to get client Ip Address in Java HttpServletRequest

前端 未结 4 1022
时光取名叫无心
时光取名叫无心 2020-12-25 12:07

I am trying to develop a Java web application (Servlet) which I need to get clients IP address.

Following is my code so far:



        
相关标签:
4条回答
  • 2020-12-25 12:25

    Try this one,

    String ipAddress = request.getHeader("X-FORWARDED-FOR");  
    if (ipAddress == null) {  
        ipAddress = request.getRemoteAddr();  
    }
    

    reference : http://www.mkyong.com/java/how-to-get-client-ip-address-in-java/

    0 讨论(0)
  • 2020-12-25 12:33
     import java.net.UnknownHostException;
    
    /**
     * Simple Java program to find IP Address of localhost. This program uses
     * InetAddress from java.net package to find IP address.
     *
     */
    public class IPTest { 
    
    public static void main(String args[]) throws UnknownHostException {
    
        InetAddress addr = InetAddress.getLocalHost();
    
        //Getting IPAddress of localhost - getHostAddress return IP Address
        // in textual format
        String ipAddress = addr.getHostAddress();
    
        System.out.println("IP address of localhost from Java Program: " + ipAddress);
    
        //Hostname
        String hostname = addr.getHostName();
        System.out.println("Name of hostname : " + hostname);     
    }
    }
    

    Output:

    IP address of localhost from Java Program: 190.12.209.123
    Name of hostname : PCLOND3433
    
    0 讨论(0)
  • 2020-12-25 12:37

    In case, you are trying to get the IP-address for Dev-environment then you can use this:-

    public String processRegistrationForm(HttpServletRequest request)
    {
        String appUrl = request.getScheme() + "://"+ request.getLocalAddr();
        return appUrl;
    }
    

    The request.getLocalAddr() will return the IP-address of the request receiving system.

    Hope it helps.

    0 讨论(0)
  • 2020-12-25 12:38

    Try this one. for all condition

    private static final String[] HEADERS_TO_TRY = {
                "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" };
    
    private String getClientIpAddress(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
    
        return request.getRemoteAddr();
    }
    
    0 讨论(0)
提交回复
热议问题