思路:
利用ip和ip區(qū)間兩端的值調(diào)用ipisvalid方法。
(視頻教程推薦:java課程)
工具類:
import org.apache.commons.lang.stringutils;import org.springframework.web.context.request.requestcontextholder;import org.springframework.web.context.request.servletrequestattributes;import javax.servlet.http.httpservletrequest;public class iputil { / * 獲得當前ip * @return */ public static string getip(){ servletrequestattributes servletrequestattributes = (servletrequestattributes) requestcontextholder.getrequestattributes(); if(servletrequestattributes == null) { return "127.0.0.1"; } httpservletrequest request = servletrequestattributes.getrequest(); 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.getheader("http_client_ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) { ip = request.getheader("http_x_forwarded_for"); } if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) { ip = request.getremoteaddr(); } if ("0:0:0:0:0:0:0:1".equals(ip)) { ip = "127.0.0.1"; } return ip; } / * 判斷ip是否在指定范圍 * @param ipstart * @param ipend * @param ip * @return */ public static boolean ipisvalid(string ipstart,string ipend, string ip) { if (stringutils.isempty(ipstart)) { throw new nullpointerexception("起始ip不能為空!"); } if (stringutils.isempty(ipend)) { throw new nullpointerexception("結(jié)束ip不能為空!"); } if (stringutils.isempty(ip)) { throw new nullpointerexception("ip不能為空!"); } ipstart = ipstart.trim(); ipend = ipend.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 (!ipstart.matches(regx_ip) || !ip.matches(regx_ip) || !ipend.matches(regx_ip)) { return false; } string[] sips = ipstart.split("\\\\\\\\."); string[] sipe = ipend.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; }} 相關(guān)教程推薦:java入門教程