java 判断IP V4是内网IP的方法

x33g5p2x  于2022-03-29 转载在 Java  
字(1.0k)|赞(0)|评价(0)|浏览(691)

分析IP,有可能涉及到判断他是内网IP还是外网IP,此方法可以用来判断内外网IP

  1. /**
  2. * @program: aws_s3
  3. * @description:
  4. * @author: sunyuhua
  5. * @create: 2022-03-28 17:39
  6. **/
  7. public class IpUtils {
  8. public static void main(String[] args) {
  9. System.out.println(internalIp("192.168.124.17"));
  10. }
  11. /**
  12. * 将string转化为byte[]
  13. * @param ipAdd
  14. * @return
  15. */
  16. public static byte[] ipv4Address2BinaryArray(String ipAdd){
  17. byte[] binIP = new byte[4];
  18. String[] strArray = ipAdd.split("\\.");
  19. for(int i=0;i<strArray.length;i++){
  20. binIP[i] = (byte) Integer.parseInt(strArray[i]);
  21. }
  22. return binIP;
  23. }
  24. public static boolean internalIp(String ipAddress) {
  25. byte[] address=ipv4Address2BinaryArray(ipAddress);
  26. final byte b0 = address[0];
  27. final byte b1 = address[1];
  28. //10.x.x.x/8
  29. final byte SECTION_1 = 0x0A;
  30. //172.16.x.x/12
  31. final byte SECTION_2 = (byte) 0xAC;
  32. final byte SECTION_3 = (byte) 0x10;
  33. final byte SECTION_4 = (byte) 0x1F;
  34. //192.168.x.x/16
  35. final byte SECTION_5 = (byte) 0xC0;
  36. final byte SECTION_6 = (byte) 0xA8;
  37. switch (b0) {
  38. case SECTION_1:
  39. return true;
  40. case SECTION_2:
  41. if (b1 >= SECTION_3 && b1 <= SECTION_4) {
  42. return true;
  43. }
  44. case SECTION_5:
  45. if (b1 == SECTION_6) {
  46. return true;
  47. }
  48. default:
  49. return false;
  50. }
  51. }
  52. }

相关文章

最新文章

更多