Java判断IP是否在指定网段中,看代码
[java] view plain copy
1. /**
2. * 判断ip是否在指定网段中
3. * @author dh
4. * @param iparea
5. * @param ip
6. * @return boolean
7. */
8. public static boolean ipIsInNet(String iparea, String ip) {
9. if (iparea == null)
10. throw new NullPointerException("IP段不能为空!");
11. if (ip == null)
12. throw new NullPointerException("IP不能为空!");
13. iparea = iparea.trim();
14. ip = ip.trim();
15. 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)";
16. final String REGX_IPB = REGX_IP + "//-" + REGX_IP;
17. if (!iparea.matches(REGX_IPB) || !ip.matches(REGX_IP))
18. return false;
19. int idx = iparea.indexOf('-');
20. 0, idx).split("//.");
21. 1).split("//.");
22. "//.");
23. long ips = 0L, ipe = 0L, ipt = 0L;
24. for (int i = 0; i < 4; ++i) {
25. 8 | Integer.parseInt(sips[i]);
26. 8 | Integer.parseInt(sipe[i]);
27. 8 | Integer.parseInt(sipt[i]);
28. }
29. if (ips > ipe) {
30. long t = ips;
31. ips = ipe;
32. ipe = t;
33. }
34. return ips <= ipt && ipt <= ipe;
35. }
1. public class IpTest {
2. public static void main(String[] args) {
3. "192.168.1.127", "192.168.1.64/26"));
4. "192.168.1.2", "192.168.0.0/23"));
5. "192.168.0.1", "192.168.0.0/24"));
6. "192.168.0.0", "192.168.0.0/32"));
7. }
8. public static boolean isInRange(String ip, String cidr) {
9. "\\.");
10. int ipAddr = (Integer.parseInt(ips[0]) << 24)
11. 1]) << 16)
12. 2]) << 8) | Integer.parseInt(ips[3]);
13. int type = Integer.parseInt(cidr.replaceAll(".*/", ""));
14. int mask = 0xFFFFFFFF << (32 - type);
15. "/.*", "");
16. "\\.");
17. int cidrIpAddr = (Integer.parseInt(cidrIps[0]) << 24)
18. 1]) << 16)
19. 2]) << 8)
20. 3]);
21.
22. return (ipAddr & mask) == (cidrIpAddr & mask);
23. }
24. }