根據HttpServletRequest獲取使用者IP地址及判斷當前IP是否是內網IP
阿新 • • 發佈:2019-01-11
最近專案上遇到了獲取登入IP並判斷是否是內網IP的需求,在此整理一下實現方法。
首先使用者登入後,我們可以通過HttpServletRequest的request物件獲取使用者IP,但這些IP不一定是使用者的真實IP。
下面是一些常見請求頭:
X-Forwarded-For:Squid 服務代理
Proxy-Client-IP:apache 服務代理
WL-Proxy-Client-IP:weblogic 服務代理
HTTP_CLIENT_IP:有些代理伺服器
X-Real-IP:nginx服務代理
通過對請求頭的過濾,儘可能的獲取真實IP:
String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); }
通過以上的方法可以得到當前使用者的IP,接下來就需要判斷此IP是否是內網IP。
內網IP通常是下面幾個網段的IP,使用者可以自己設定:
10.0.0.0~10.255.255.255
172.16.0.0~172.31.255.255
192.168.0.0~192.168.255.255
確定了以上網段,接下來只需要做判斷IP是否屬於以上3個網段就行了:
public boolean isInner(String ip) { String reg = "((192\\.168|172\\.([1][6-9]|[2]\\d|3[01]))" + "(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){2}|" + "^(\\D)*10(\\.([2][0-4]\\d|[2][5][0-5]|[01]?\\d?\\d)){3})"; Pattern p = Pattern.compile(reg); Matcher matcher = p.matcher(ip); return matcher.find(); }
下面附上私有網段的正則表示式:
A類地址範圍:10.0.0.0—10.255.255.255 正則表示式 ^10\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$ B類地址範圍:172.16.0.0---172.31.255.255 正則表示式 ^172\.(1[6789]|2[0-9]|3[01])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$ C類地址範圍:192.168.0.0---192.168.255.255 正則表示式 ^192\.168\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])$