본문 바로가기

Programming/java

[java] Client IP 조회

Client IP 조회



서버에 접속하는 클라이언트의 아이피를 확인하기 위해서는

HttpServletRequest 객체를 이용하면 된다고 한다.

request.getRemoteAddr();



하지만 Load Balancer나 프록시 같은 경우는 정확한 아이피 정보를

가져오지 못 한다고 한다. 


그래서 다음과 같은 메소드를 이용한다.

localhost에서 테스트 할 경우 0:0:0:0:0:0:0:1 값으로 넘어 오는 경우가 있는데

이 값은 IPv6에서 IPv4의 127.0.0.1와 같은 값이다.


127.0.0.1로 받아오려면 톰캣 vm arguments에 아래와 같이 추가하여 준다.


vm arguments

-Djava.net.preferIPv4Stack=true 


java

 public String getClientIP(HttpServletRequest request) {


     String ip = request.getHeader("X-FORWARDED-FOR"); 

     

     if(ip == null || ip.length() == 0) {

         ip = request.getHeader("Proxy-Client-IP");

     }

     if(ip == null || ip.length() == 0) {

         ip = request.getHeader("WL-Proxy-Client-IP");  // 웹로직

     }

     if(ip == null || ip.length() == 0) {

         ip = request.getRemoteAddr() ;

     }

     return ip;

 }






2.

import java.net.*;


만약 공인 IP없으면 내부 IP 가져오도록 처리


public static String getCurrentEnvironmentNetworkIp(){

        Enumeration netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return getLocalIp();
        }

        while (netInterfaces.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface)netInterfaces.nextElement();
            Enumeration address = ni.getInetAddresses();
            if (address == null) {
                return getLocalIp();
            }
            while (address.hasMoreElements()) {
                InetAddress addr = (InetAddress)address.nextElement();
                if (!addr.isLoopbackAddress() && !addr.isSiteLocalAddress() && !addr.isAnyLocalAddress() ) {
                    String ip = addr.getHostAddress();
                    if( ip.indexOf(".") != -1 && ip.indexOf(":") == -1 ){
                        return ip;
                    }
                }
            }
        }
        return getLocalIp();
    }

    public static String getLocalIp(){
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return null;
        }
    }