JAVA判斷某個IP是否在指定IP段內
阿新 • • 發佈:2019-01-28
用JAVA實現了一個判斷某個IP是否在指定IP段內的方法,方便網站上使用黑白名單功能,有兩種方法,推薦使用方法一。
public class testIP { /** * 判斷IP是否在指定IP段內,方法一(推薦) * ipRange IP段(以'-'分隔) * * @param ipRange * @param ip * @return boolean */ public static boolean ipIsInRange(String ip, String ipRange) { if (ipRange == null) throw new NullPointerException("IP段不能為空!"); if (ip == null) throw new NullPointerException("IP不能為空!"); ipRange = ipRange.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 (!ipRange.matches(REGX_IPB) || !ip.matches(REGX_IP)) return false; int idx = ipRange.indexOf('-'); String[] sips = ipRange.substring(0, idx).split("\\."); String[] sipe = ipRange.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; } /* * 判斷IP是否在指定IP段內,方法二 * ipRange IP段(以'-'分隔) * * @param ipRange * @param ip * @return boolean */ public static boolean ipInRange(String ip, String ipRange) { int idx = ipRange.indexOf('-'); String beginIP = ipRange.substring(0, idx); String endIP = ipRange.substring(idx + 1); return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP); } public static long getIp2long(String ip) { String[] ips = ip.split("\\."); long ip2long = 0L; for (int i = 0; i < 4; ++i) { ip2long = ip2long << 8 | Integer.parseInt(ips[i]); } return ip2long; } public static void main(String[] args) { // 判斷192.168.1.100 是否在IP段192.168.1.1-192.168.1.254內 String ip = "192.168.18.100"; String ipRange = "192.168.1.1-192.168.1.254"; boolean isInRange = ipIsInRange(ip, ipRange); //boolean isInRange = ipInRange(ip, ipRange); System.out.println(isInRange); }
完!