Java get visitors Ip Ip and restrict access page

Original link: https://www.zjhuiwan.cn/info/20200330/4006602464505049.html

Recently I met a demand, a website can only access the network, ip need to limit access. Ip is in the part of the article to the site only in the white list is opened. Because the site is static, all articles are static html page. So first thought is to get visitors directly js ip and then determine whether or not in the white list, not in the whitelist, the page does not have permission.

But JS get the network Ip is quite troublesome, finally found a few ways tried not work.

Several methods and methods found at last achieved the record.

JS method for obtaining external network ip:

// The easiest way to get outside the network ip. It can be used directly, but with nothing ..
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script>
    document.write(returnCitySN["cip"]); </script>

JS obtain network Ip method: // Some browsers acquired encryption ip of a problem, so when its time

function getIP(callback) {
        let recode = {};         let RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;         // 如果不存在则使用一个iframe绕过         if (!RTCPeerConnection) {             // 因为这里用到了iframe,所以在调用这个方法的script上必须有一个iframe标签             // <iframe id="iframe" sandbox="allow-same-origin" style="display:none;"></iframe>             let win = iframe.contentWindow;             RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;         }         //创建实例,生成连接         let pc = new RTCPeerConnection();         // 匹配字符串中符合ip地址的字段         function handleCandidate(candidate) { debugger;             let ip_regexp = /([0-9]{1,3}(\.[0-9]{1,3}){3}|([a-f0-9]{1,4}((:[a-f0-9]{1,4}){7}|:+[a-f0-9]{1,4}){6}))/;             let ip_isMatch = candidate.match(ip_regexp)[1];             if (!recode[ip_isMatch]) {                 callback(ip_isMatch);                 recode[ip_isMatch] = true;             }         }         //监听icecandidate事件         pc.onicecandidate = (ice) => {             if (ice.candidate) {                 handleCandidate(ice.candidate.candidate);             }         };         //建立一个伪数据的通道         pc.createDataChannel('');         pc.createOffer((res) => {             pc.setLocalDescription(res);         }, () => {});         //延迟,让一切都能完成         setTimeout(() => {             let lines = pc.localDescription.sdp.split('\n');             lines.forEach(item => {                 if (item.indexOf('a=candidate:') === 0) {                     handleCandidate(item);                 }             })         }, 1000);     } getIP(function (ip) { alert(ip); });

Use WebRTC get in the real network Ip, WebRTC support is a web browser for real-time voice conversations or video conversation API

Since WebRTC in establishing the connection, the local address will be sent to the other party SDP, can be obtained by visiting the visitor's IP SDP

But some browsers impossible, so in this way or give up.

 

 

Finally, still feel relatively well implemented in Java, the front page article write ajax, each entry article first determine whether the articles need to restrict access to IP, if you need to request at the back-end, back-end acquisition Ip determine whether the whitelist. Note ajax use synchronization.

Visitors Ip get Java method:

 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);

The complete code

    
/**
     * 判断文章是否有权可看
     * 
     * @param map
     * @return
     */
    @RequestMapping("/isIntranet.do")     @ResponseBody     public String isIntranet(ServletRequest request, ServletResponse response) {         Map<String, Object> map = new HashMap<String, Object>();         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<Object> objects = prop.keySet();             for (Object object : objects) {                 String ipNot = new String(prop.getProperty((String)object).getBytes("iso-8859-1"), "gbk");                 System.out.println(ipNot);                 /*result = ipIsValid("192.168.8.78-192.168.255.255", ip) || ipIsValid("172.16.0.0-172.31.255.255", ip)                     || ipIsValid("10.0.0.0-10.255.255.255", ip);*/                 result = ipIsValid(ipNot, ip);             }             in.close();         } catch (IOException e) {             e.printStackTrace();         }         return result;     }          //校验Ip是否包含在Ip段内     public static boolean ipIsValid(String ipSection, String ip) {         if (ipSection == null) {             throw new NullPointerException("IP段不能为空!");         }         if (ip == null) {             throw new NullPointerException("IP不能为空!");         }         ipSection = ipSection.trim();         ip = ip.trim();         final String REGX_IP =             "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";         final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;         if (!ipSection.matches(REGX_IPB) || !ip.matches(REGX_IP)) {             return false;         }         int idx = ipSection.indexOf('-');         idx = idx < 0 ? ipSection.length() : idx;         String[] sips = ipSection.substring(0, idx).split("\\.");         String[] sipe = ipSection.substring(idx + 1).split("\\.");         String[] sipt = ip.split("\\.");         long ips = 0L, ipe = 0L, ipt = 0L;         for (int i = 0; i < 4; ++i) {             ips = ips << 8 | Integer.parseInt(sips[i]);             ipe = ipe << 8 | Integer.parseInt(sipe[i]);             ipt = ipt << 8 | Integer.parseInt(sipt[i]);         }         if (ips > ipe) {             long t = ips;             ips = ipe;             ipe = t;         }         return ips <= ipt && ipt <= ipe;     }

The method of the above are from the network, the effective pro-test, recording thereto.

I am just a porter

Guess you like

Origin www.cnblogs.com/sunonzj/p/12597600.html
Recommended