本文共 6185 字,大约阅读时间需要 20 分钟。
原文链接:
最近遇到一个需求,一个只能内网访问的网站,需要限制ip访问。就是网站内的部分文章只有白名单内的ip才能打开。因为是静态化的网站,所有文章都是静态html页面。所以首先想到的就是直接js获取访问者ip然后再判断是否在白名单内,不在白名单内就到没有权限页面。
但是JS获取内网Ip还是比较麻烦的,查到几个方法最后试了都不行。
记录下查到的几个方法和最后实现的方法。
JS获取外网ip的方法:
//最简单的获取外网ip的方法。可以直接用,但是没啥用..
JS获取内网Ip的方法://有些浏览器获取到的加密ip段有问题,所以当其时期
function getIP(callback) { let recode = {}; let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; // 如果不存在则使用一个iframe绕过 if (!RTCPeerConnection) { // 因为这里用到了iframe,所以在调用这个方法的script上必须有一个iframe标签 //
利用WebRTC获取真实内网Ip,WebRTC是一个支持网页浏览器进行实时语音对话或视频对话的API
由于WebRTC在建立连接过程中,会向对方发送本地地址SDP,因此可以通过访问SDP获得访问者的IP
但是有些浏览器用不了,所以还是放弃这种方式了。
最后还是觉得用Java来实现比较好吧,前端文章页写个ajax,每次进入文章先判断文章是否需要限制IP访问,如果需要就请求下后端,后端获取Ip判断是否在白名单内。注意ajax要用同步。
Java获取访问者Ip方法:
String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } System.out.println(ip);
完整代码
/** * 判断文章是否有权可看 * * @param map * @return */ @RequestMapping("/isIntranet.do") @ResponseBody public String isIntranet(ServletRequest request, ServletResponse response) { Mapmap = new HashMap (); HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; // 判断访问者Ip是否白名单内 boolean flag = isIPOK(req, resp); System.out.println(flag); if (flag) { return "true"; } else { return "false"; } } private boolean isIPOK(HttpServletRequest request, HttpServletResponse response) { // String accessIP = IPUtil.getUserIp(request); String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "nuknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } System.out.println(ip); return isLAN(ip); } // 是否为内网网段 public boolean isLAN(String ip) { if ("127.0.0.1".equals(ip)) { return true; } boolean result = true; try { Properties prop = new Properties(); //获取设置Ip段的配置文件 InputStream in = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties"); prop.load(in); // 遍历取值 Set
以上方法均来自网络,亲测有效,记录于此。
I am just a porter
转载地址:http://omwxi.baihongyu.com/