title: Get real client IP in a Servlet
body: <p>I'm having some trouble with a simple problem. I would get the <strong>real client IP inside an HTTPServlet</strong>. </p>
  
  <p>Since now I used:</p>
  
  <pre><code>request.getRemoteAddr()
  </code></pre>
  
  <p>But now it returns a false IP. eg: xxx.xxx.xxx.<strong>50</strong> but my IP is something like xxx.xxx.xxx.<strong>159</strong>. (checked at <a href="http://whatismyipaddress.com/" rel="noreferrer">http://whatismyipaddress.com/</a>). </p>
  
  <p>Now I tried to use:</p>
  
  <pre><code>request.getHeader("X-Forwarded-For")
  </code></pre>
  
  <p>It returns NULL.</p>
  
  <p>I also took a probe with the following class:</p>
  
  <pre><code>public class IpUtils {
  
  public static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
  public static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$");
  
  public static String longToIpV4(long longIp) {
      int octet3 = (int) ((longIp &gt;&gt; 24) % 256);
      int octet2 = (int) ((longIp &gt;&gt; 16) % 256);
      int octet1 = (int) ((longIp &gt;&gt; 8) % 256);
      int octet0 = (int) ((longIp) % 256);
  
      return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
  }
  
  public static long ipV4ToLong(String ip) {
      String[] octets = ip.split("\\.");
      return (Long.parseLong(octets[0]) &lt;&lt; 24) + (Integer.parseInt(octets[1]) &lt;&lt; 16)
              + (Integer.parseInt(octets[2]) &lt;&lt; 8) + Integer.parseInt(octets[3]);
  }
  
  public static boolean isIPv4Private(String ip) {
      long longIp = ipV4ToLong(ip);
      return (longIp &gt;= ipV4ToLong("10.0.0.0") &amp;&amp; longIp &lt;= ipV4ToLong("10.255.255.255"))
              || (longIp &gt;= ipV4ToLong("172.16.0.0") &amp;&amp; longIp &lt;= ipV4ToLong("172.31.255.255"))
              || longIp &gt;= ipV4ToLong("192.168.0.0") &amp;&amp; longIp &lt;= ipV4ToLong("192.168.255.255");
  }
  
  public static boolean isIPv4Valid(String ip) {
      return pattern.matcher(ip).matches();
  }
  
  public static String getIpFromRequest(HttpServletRequest request) {
      String ip;
      boolean found = false;
      if ((ip = request.getHeader("x-forwarded-for")) != null) {
          StringTokenizer tokenizer = new StringTokenizer(ip, ",");
          while (tokenizer.hasMoreTokens()) {
              ip = tokenizer.nextToken().trim();
              if (isIPv4Valid(ip) &amp;&amp; !isIPv4Private(ip)) {
                  found = true;
                  break;
              }
          }
      }
  
      if (!found) {
          ip = request.getRemoteAddr();
      }
  
      return ip;
  }
  }
  </code></pre>
  
  <p>It also returned the xxx.xxx.xxx.50 IP. :( </p>
  
  <p>Now I don't know how to get the real client IP. If somebody knows the solution please make an answer.</p>