HttpServletRequest getRemoteAddr () does not work as I expect

The following code returns incorrectly from what I understand:

HttpServletRequest httpRequest = (HttpServletRequest) request; String userIPAddress = httpRequest.getRemoteAddr(); // Actual // "0:0:0:0:0:0:0:1%0" // Expected // "0:0:0:0:0:0:0:1" 

Any idea why there is% 0? When i walk through

 InetAddress.getAllByName("localhost") 

I get the following:

 // ["192.168.100.1", "127.0.0.1", "0:0:0:0:0:0:1"] 

How can I check localhost if getRemoteAddr () returns the wrong format, or am I doing something wrong?

Thanks!

+6
source share
2 answers

The problem is that these two functions

1) java.net.InetAddress.getAllByName (String)

and

2) javax.servlet.ServletRequest.getRemoteAddr ()

Very different. The first function is part of the standard Java runtime, and the second is implemented by your Java EE container. You are using Tomcat7 to add the optional zone parameter% 0.

On the bottom line, you should not do string comparisons by IP addresses like you do.

What you really have to do is use org.apache.catalina.filters.RemoteIpFilter . It does what you are trying to do in a certain way.

Example:

 <filter> <filter-name>RemoteIpFilter</filter-name> <filter-class>org.apache.catalina.filters.RemoteIpFilter</filter-class> <init-param> <param-name>allowedInternalProxies</param-name> <param-value>192\.168\.0\.10|192\.168\.0\.11</param-value> </init-param> <init-param> <param-name>remoteIpHeader</param-name> <param-value>x-forwarded-for</param-value> </init-param> <init-param> <param-name>remoteIpProxiesHeader</param-name> <param-value>x-forwarded-by</param-value> </init-param> <init-param> <param-name>protocolHeader</param-name> <param-value>x-forwarded-proto</param-value> </init-param> </filter> 

See http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#Remote_IP_Filter for details.

+4
source

0:0:0:0:0:0:0:1%0 is a valid long form for the local IPv6 host. %0 indicates an optional zone index.

Read more about IPv6 Zone Indices .

I do not know why calling httpRequest.getRemoteAddr(); returns the optional zone index% 0 and

 InetAddress.getAllByName("localhost") 

not. However, my recommendation is that if you are looking for a match on localhost, you agree to both patterns or execute matchWith.

+2
source

Source: https://habr.com/ru/post/923514/


All Articles