Port-forwarding 和 HttpServletRequest 和一个疏忽引发的bug

来源:互联网 发布:英雄联盟辅助软件 编辑:程序博客网 时间:2024/05/17 03:39

最近接手了一个bug,很诡异:产品发布的webservice不work了,报错:Connection refused.

查了一下,报错的webservice调用都来自于服务器本机,也就是说在本机的code中调用在本机上发布的webservice。挺丑陋,但不至于报错。

一番狠查之后发现从client 端到服务器并不能直接访问,而是经过了NAT port-forwarding 把针对公网server的request映射到私网server上,不但IP映射了,对端口也进行了映射,也就是说client端调用的url: http://IP:PORT并不是真实server的IP和http监听的port, 这些都是公网机的IP和port, 公网机收到请求后进行映射,最终映射到私网IP和port上。

OK,这也没问题,因为不涉及到调用本机webservice的部分都正常。查了code中对本机webservice的调用方式发现了以下代码:

servletRequest.getServerPort()

咋一看没啥问题,仔细一看还真有问题,以下是JAVA-API的解释:

 getServerPort    public int 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.        Returns:          an integer specifying the port number   

意思是返回值是client端请求url中的port, 从上面说明得知,这个port 其实并不是真正server的port而是公网机的,哈,问题原来出在这里! 那怎么fix呢?

 getLocalPort    public int getLocalPort()        Returns the Internet Protocol (IP) port number of the interface on which the request was received.        Returns:          an integer specifying the port number      Since:          2.4   

在没有port-forwarding的情况下,这两个API的返回时一样样的,但是本case中就大相径庭了,这也说明了为什么这个bug在出厂时并没被发现的原因。

就此记录,已被后查,写的比较乱,any comment please free let me know.