All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xiongyingqi.common.utils.ip.IpMaskUtils Maven / Gradle / Ivy

The newest version!
package com.xiongyingqi.common.utils.ip;

import com.xiongyingqi.common.utils.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author xiongyingqi
 * @since 17-5-8 下午9:13
 */
public abstract class IpMaskUtils {
  private static final Logger logger = LoggerFactory.getLogger(IpMaskUtils.class);

  public static int convertIpAddressToInt(String ipString) throws UnknownHostException {
    Inet4Address inet4Address = (Inet4Address) InetAddress.getByName(ipString);
    byte[] ipBytes = inet4Address.getAddress();
    int ip = ((ipBytes[0] & 0xFF) << 24) |
        ((ipBytes[1] & 0xFF) << 16) |
        ((ipBytes[2] & 0xFF) << 8) |
        ((ipBytes[3] & 0xFF) << 0);
    return ip;
  }


  public static int[] parseSubnetConfig(String subnetConfig) {
    Assert.hasText(subnetConfig, "Subnet config is null!");
    String[] subnetAndMask = subnetConfig.split("/");
    Integer ip = null;
    Integer bits = 0;
    if (subnetAndMask.length == 1) {
      try {
        ip = convertIpAddressToInt(subnetAndMask[0]);
      } catch (Exception e) {
        logger.error("Illegal ip format: " + subnetConfig + ", message: " + e.getMessage(), e);
      }
    } else {
      try {
        ip = convertIpAddressToInt(subnetAndMask[0]);
        bits = Integer.parseInt(subnetAndMask[1]);
      } catch (Exception e) {
        logger.error("Illegal ip format: " + subnetConfig + ", message: " + e.getMessage(), e);
      }
    }
    Assert.notNull(ip, "Illegal config format! format: 192.168.0.1 or 192.168.0.1/16");
    if (logger.isDebugEnabled()) {
      logger.debug("Parse subnetConfig: {} to subnet: {} bits: {}", new Object[] {subnetConfig, ip, bits});
    }
    return new int[] {ip, bits};
  }

  public static boolean isIpInMask(String ipString, String config) throws UnknownHostException {
    int ip = convertIpAddressToInt(ipString);
    int[] subnetAndBits = parseSubnetConfig(config);
    int subnet = subnetAndBits[0];
    int bits = subnetAndBits[1];
    return isIpInMask(ip, subnet, bits);
  }

  public static boolean isIpInMask(int ip, int subnet, int bits) {
    // Create bitmask to clear out irrelevant bits. For 10.1.1.0/24 this is
    // 0xFFFFFF00 -- the first 24 bits are 1's, the last 8 are 0's.
    //
    //     -1        == 0xFFFFFFFF
    //     32 - bits == 8
    //     -1 << 8   == 0xFFFFFF00
    int mask = -1 << (32 - bits);

    boolean b = (subnet & mask) == (ip & mask);
    if (logger.isDebugEnabled()) {
      logger.debug("({} & {})(subnet & mask): {}, ({} & {})(ip & mask): {}", new Object[] {Integer.toHexString(subnet),
          Integer.toHexString(mask), Integer.toHexString(subnet & mask), Integer.toHexString(ip),
          Integer.toHexString(mask), Integer.toHexString(ip & mask)});
    }
    return b;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy