Forum: Common

Here is a forum space for Server: Common.

137. How do ProPTT2 server define client's IP?

Below is server's code to detect a client's IP.

static public String getClientIP(HttpServletRequest request)
{
	String forwardedIp = request.getHeader("X-Forwarded-For");
	if(forwardedIp!=null && forwardedIp.isEmpty()==false)
	{
		if(forwardedIp.indexOf(',')<0) return forwardedIp;
		StringTokenizer st = new StringTokenizer(forwardedIp, ",");
		if(st.hasMoreTokens())
		{
			String param = st.nextToken();
			return param;
		}
	}
	forwardedIp = request.getHeader("X-Forwarded-IP");
	if(forwardedIp!=null && forwardedIp.isEmpty()==false)
	{
		if(forwardedIp.indexOf(',')<0) return forwardedIp;
		StringTokenizer st = new StringTokenizer(forwardedIp, ",");
		if(st.hasMoreTokens())
		{
			String param = st.nextToken();
			return param;
		}
	}
	forwardedIp = request.getHeader("Forwarded");
	if(forwardedIp!=null && forwardedIp.isEmpty()==false) 
	{
		StringTokenizer st = new StringTokenizer(forwardedIp, ";");
		while(st.hasMoreTokens())
		{
			String param = st.nextToken();
			StringTokenizer st2 = new StringTokenizer(param, "=");
			if(st2.countTokens() == 2)
    		{
				String name = st2.nextToken().trim();
				String value = st2.nextToken().trim();
				if(name.equals("for") && value.startsWith("\"")==false && value.startsWith("unknown")==false)
				{
					return value;
				}
    		}
		}
		if(forwardedIp.indexOf(',')>0)
		{
			st = new StringTokenizer(forwardedIp, ",");
    		while(st.hasMoreTokens())
    		{
    			String param = st.nextToken();
    			StringTokenizer st2 = new StringTokenizer(param, "=");
    			if(st2.countTokens() == 2)
        		{
    				String name = st2.nextToken().trim();
    				String value = st2.nextToken().trim();
    				if(name.equals("for") && value.startsWith("\"")==false && value.startsWith("unknown")==false)
    				{
    					return value;
    				}
        		}
    		}
		}
	}
	String clientIp = request.getRemoteAddr();
	return clientIp;
}

Apr 25 '20 at 16:12 (GMT0) created by ProPTT2 dev