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

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

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

/**
 * @program: aws_s3
 * @description:
 * @author: sunyuhua
 * @create: 2022-03-28 17:39
 **/
public class IpUtils {

 public static void main(String[] args) {
   System.out.println(internalIp("192.168.124.17"));
 }

 /**
  * 将string转化为byte[]
  * @param ipAdd
  * @return
  */
 public static byte[] ipv4Address2BinaryArray(String ipAdd){
  byte[] binIP = new byte[4];
  String[] strArray = ipAdd.split("\\.");
  for(int i=0;i<strArray.length;i++){
   binIP[i] = (byte) Integer.parseInt(strArray[i]);
  }
  return binIP;
 }

 public static boolean internalIp(String ipAddress) {
  byte[] address=ipv4Address2BinaryArray(ipAddress);
  final byte b0 = address[0];
  final byte b1 = address[1];
  //10.x.x.x/8
  final byte SECTION_1 = 0x0A;
  //172.16.x.x/12
  final byte SECTION_2 = (byte) 0xAC;
  final byte SECTION_3 = (byte) 0x10;
  final byte SECTION_4 = (byte) 0x1F;
  //192.168.x.x/16
  final byte SECTION_5 = (byte) 0xC0;
  final byte SECTION_6 = (byte) 0xA8;
  switch (b0) {
   case SECTION_1:
    return true;
   case SECTION_2:
    if (b1 >= SECTION_3 && b1 <= SECTION_4) {
     return true;
    }
   case SECTION_5:
    if (b1 == SECTION_6) {
     return true;
    }
   default:
    return false;

  }
 }
}

相关文章

最新文章

更多