开发者

Difference between getLocalPort() and getServerPort() in servlets

开发者 https://www.devze.com 2022-12-18 15:38 出处:网络
I am studying servlets, I have come up with a doubt difference betw开发者_运维问答een getLocalPort() and getServerPort().

I am studying servlets, I have come up with a doubt difference betw开发者_运维问答een getLocalPort() and getServerPort(). Here the getLocalPort() means server side only then whats the meaning of getServerPort()?

Thanks.


In a simple setup (where your application server/servlet container accepts the request of the client directly) both methods will return the same value.

When the servlet container is not the application that accepts the client request (for example when you use an Apache HTTP server with mod_jk to accept the request and forward the request to a Tomcat instance via AJP), then getServerPort() will return the port the client connected to (probably 80, when the default port is used) and getLocalPort() will return the port that Tomcat used to accept the connection from the HTTP server (probably 8009 or something similar).


Let's see what the javadoc is saying about getLocalPort():

Returns the Internet Protocol (IP) port number of the interface on which the request was received.

And this is what we can read about getServerPort():

Returns the port number to which the request was sent. It is the value of the part after ":" in the Host header value, if any, or the server port where the client connection was accepted on.

So, if a client sends a request to http://mydomain.com:80/ that is then "routed" to a container listening on another port (and maybe another machine), getServerPort() will return 80 and getLocalPort() will return the port of the container to which the request was forwarded, let's say 7001 for a WebLogic instance listening to that port.


I looked at Jetty and Tomcat's implementation of the server port, and this is my findings:

  1. When request URL has a port number in it (e.g. http(s)://website.com:8888/blah/blah-blah), the getServerPort() always return what was included in the request URL (in the example, 8888)
  2. When request URL does not have a port number in it, then
    • 443 will be returned if
      • Tomcat sees SSLEnabled=true
      • Jetty sees schema=https
    • 80 will be returned if
      • sees SSLEnabled=false
      • Jetty sees schema=http

Therefore, getServerPort() has nothing to do with apache HTTP server or load balancer sitting in front of it (if any), or IP table routes sitting on Tomcat/Jetty server. They will always return standard port number based on http/https, unless a port number is specified in the request URL.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号