1 /* 判断是否是内网IP */ 2 public static boolean isInnerIP(String ipAddress) { 3 boolean isInnerIp = false; 4 long ipNum = getIpNum(ipAddress); 5 /** 6 * 私有IP:A类 10.0.0.0-10.255.255.255 B类 172.16.0.0-172.31.255.255 C类 7 * 192.168.0.0-192.168.255.255 当然,还有127这个网段是环回地址 8 **/ 9 long aBegin = getIpNum("10.0.0.0"); 10 long aEnd = getIpNum("10.255.255.255"); 11 long bBegin = getIpNum("172.16.0.0"); 12 long bEnd = getIpNum("172.31.255.255"); 13 long cBegin = getIpNum("192.168.0.0"); 14 long cEnd = getIpNum("192.168.255.255"); 15 isInnerIp = isInner(ipNum, aBegin, aEnd) 16 || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd) 17 || ipAddress.equals("127.0.0.1"); 18 return isInnerIp; 19 } 20 21 /* 获取IP数 */ 22 private static long getIpNum(String ipAddress) { 23 String[] ip = ipAddress.split("\\."); 24 long a = Integer.parseInt(ip[0]); 25 long b = Integer.parseInt(ip[1]); 26 long c = Integer.parseInt(ip[2]); 27 long d = Integer.parseInt(ip[3]); 28 long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d; 29 return ipNum; 30 } 31 32 private static boolean isInner(long userIp, long begin, long end) { 33 return (userIp >= begin) && (userIp <= end); 34 }
1 public static void main(String[] args) { 2 String begin = "222.177.202.0"; 3 String end = "222.177.202.255"; 4 String userIP = "222.177.202.11";//客户端IP 5 long a = getIpNum(begin); 6 long b = getIpNum(end); 7 long c = getIpNum(userIP); 8 if(isInner(Long.valueOf(c),Long.valueOf(a),Long.valueOf(b))){ 9 System.out.println("在范围内"); 10 }else{ 11 System.out.println("在范围外"); 12 } 13 }