IPV6工具类 java

import com.hdlh.network.common.Constatnts;
import org.apache.commons.lang.StringUtils;


import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 
 * ipv6工具类
 */
public class IPV6Utils {
   public static String IPV6START = "0:0:0:0:0:0:0:0";
   public static String IPV6END = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff";
   private static String reg = "^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}"
         + "(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))"
         + "|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)"
         + "(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|"
         + "((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))"
         + "|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|"
         + "[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|"
         + "((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)"
         + ")|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:"
         + "((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|"
         + "(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)"
         + "(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$";
   private static Pattern pattern = Pattern.compile(reg);
   
   /**
    * 包含ipv6
    * @param ip
    * @return
    */
   public static boolean  checkIpv6(String ip){
      try{
         if(ip.contains("/")){
            String tempIp = ip.split("/")[0];
            int mask = Integer.valueOf(ip.split("/")[1]);
            if(pattern.matcher(tempIp).find()&&(mask>=0&&mask<=128)){
               return true;
            }
         }else{
            if(pattern.matcher(ip).find()){
               return true;
            }
         }
      }catch(Exception e){
         //e.printStackTrace();
         return false;
      }
      
      return false;
   }
   
   /**
    * 
    * @Title: FormatIpMask  
    * @Description: TODO(格式化IPV6)  
    * @param ips
    * @return
    */
   public static List<String> FormatIpMask(List<String> ips){
      List<String> results = new ArrayList<String>();
      for (String ip : ips) {
         if(ip.contains("/")){//带掩码,不处理
            String tmps[] = ip.split("/");//格式化IPV6
            results.add(getStartIp(tmps[0], toMask(Integer
                  .valueOf(tmps[1])))+"/"+tmps[1]);
         }else{
            results.add(ip+"/128");
         }
      }
      return results;
   }
   
   public static String replaceFirstZero(String ip){
      String[] ips = ip.split(":");
      String tmp =null;
      for(int i= 0;i<ips.length;i++){
         ips[i] = "".equals(tmp=ips[i].replaceFirst("^0*", ""))?"0":tmp;
      }
      return  StringUtils.join(ips, ":");
   }
   /**
    * 16进制IPV6 补全分号
    * 20010DB81428142814281428142888fe -> 2001:0db8:1428:1428:1428:1428:1428:88fe
    * @param ipv6
    * @return
    */
   public static String ipv6AddSemicolon( String ipv6){
      String ip = ipv6.replaceAll ( "(.{4})", "$1:").toLowerCase();
      if(ip.endsWith(":"))
         ip = ip.substring(0, ip.length()-1);
      return ip;
   }
   
   /**
    * 判断ip1和ip不是相邻ip ip1 -ip2 > 1  ip需排序后比较
    * @param ip1
    * @param ip2
    * @return
    */
   private static boolean ip2NextToIp1(String ip1,String ip2){
      /**
       * String ip = "1428:8eee";
         String ip2 = "1428:9000";
       */
      int length = ip1.length();
      for(int i =0;i<length;i++){
         if(ip1.charAt(i)!=ip2.charAt(i)){
            int ch = Integer.parseInt(ip1.charAt(i)+"", 16)
                  -Integer.parseInt(ip2.charAt(i)+"", 16);
            if(ch > 1){
               return true;
            }else if (ch==1){
               i++;
               for(;i<length;i++){
                  if(ip1.charAt(i)==':' 
                        || (ip1.charAt(i)=='0'
                        && (ip2.charAt(i)=='f' 
                        || ip2.charAt(i)=='F'))){
                     continue;
                  }else{
                     return true;
                  }
               }
               return false;
            }else{
               return false;
            }
         }
      }
      return false;
   }
   
   /**
    *  ipv6 0压缩还原32
    * @param ip
    * @return
    */
   public static String ipv6Format32(String ip){
      String[] split = ipv6Format(ip).split(":");
      StringBuffer sbf = new StringBuffer();
      for(String s:split){
         sbf.append(s.length()==1?"000":(s.length()==2?"00":(s.length()==3?"0":""))).append(s).append(":");
      }
      return sbf.toString().substring(0,sbf.length()-1);
   }
   /**
    *  ipv6 0压缩还原
    * @param ip
    * @return
    */
   public static String ipv6Format(String ip){
      if("::".equals(ip)){
         return IPV6START;
      }else if(ip.startsWith("::")){
         String[] ips = ip.substring(2, ip.length()).split(":");
         String[] tmp = new String[8];
         int i =ips.length;
         for(int j =7;j>=0;j--){
            if(i>0){
               tmp[j]=ips[--i];
            }else{
               tmp[j]="0";
            }
         }
         return   StringUtils.join(tmp, ":");
      }else if(ip.endsWith("::")){
         String[] ips = ip.substring(0, ip.length()-2).split(":");
         String[] tmp = new String[8];
         for(int j =0;j<=7;j++){
            if(j<ips.length){
               tmp[j]= ips[j];
            }else{
               tmp[j]= "0";
            }
         }
         return  StringUtils.join(tmp, ":");
      }else if(ip.contains("::")){
         String[] ips = ip.split(":");
         String[] tmp = new String[8];
         out:for(int i =0;i<ips.length;i++){
               if(!"".equals(ips[i])){
                  tmp[i] = ips[i];
               }else{
                  int k =ips.length;
                  for(int j =7;j>0;j--){
                     if(k-1 > i){
                        tmp[j] = ips[--k];
                     }else{
                        while(i<=j){
                           tmp[i++]="0";
                        }
                        break out;
                     }
                  }
               }
         }
         return  StringUtils.join(tmp, ":");
      }else{
         return ip;
      }
   }
   
   /**
    * ipv6 0压缩还原 速度慢,弃用  ffe:98::a23:9
    * @param ipv6
    * @return
    * @throws UnknownHostException 
    */
   public static String ipv6FormatForJDK(String ip) throws UnknownHostException{
      return InetAddress.getByName(ip).getHostName();
   }
   /**
    * 判断是否是ipv6合法地址
    * @param ip
    * @return
    */
   public static boolean isIpv6(String ip){
      //jdk1.5及以上支持
      return sun.net.util.IPAddressUtil.isIPv6LiteralAddress(ip);
   }
   
   private static int[] ipAddressSplit(String ipAddress) {
      String[] ipSplit=ipv6Format(ipAddress).split(":");
      int[] ip=new int[ipSplit.length];
      if(ipSplit.length==8){
         for(int i=0;i<ipSplit.length;i++){
            //16转10
            ip[i]=Integer.parseInt(ipSplit[i],16);
         }
      }
      return ip;
   }
   /**
    * 计算网段起始地址
    * @param ipv6
    * @param netmask
    * @return
    */
   public static String getStartIp(String ipv6,String mask) {
      int[] ipInt = ipAddressSplit(ipv6);;
      int[] netmaskInt = ipAddressSplit(mask);
      String[] temp=new String[8];
      for(int i=0;i<8;i++){
         temp[i]=Integer.toHexString(ipInt[i] & netmaskInt[i]);
      }
      return StringUtils.join(temp, ":");
   }
   /**
    * 计算网段结束地址
    * @param ipv6
    * @param netmask
    * @return
    */
   public static String getEndIp(String ipv6,String mask){
      int[] ipInt = ipAddressSplit(ipv6);
      int[] netmaskInt = ipAddressSplit(mask);
      String[] temp=new String[8];
      for(int i=0;i<8;i++){
         temp[i]=Integer.toHexString(65535-netmaskInt[i]+(ipInt[i] & netmaskInt[i]));
      }
      return StringUtils.join(temp, ":");
   }
   
   /**
    * 短掩码转长掩码
    * @param mask
    * @return
    */
   public static String toMask(int flag) {
      int num=flag/16;
      int rem=flag%16;
      int result=0;
      StringBuilder sbr=new StringBuilder();
      if(rem>0){
         for(int i=0;i<16;i++){
            if(i<rem){
               sbr.append("1");
            }else{
               sbr.append("0");
            }
         }
         result=Integer.valueOf(sbr.toString(),2);
      }
      String mask[]=new String[8];
      for(int i=0;i<8;i++){
         if(i<num){
            mask[i]="ffff";
         }else if(rem>0 && i==num){
            mask[i]=Integer.toHexString(result);
         }else{
            mask[i]="0";
         }
      }
      return StringUtils.join(mask,":");
   }
   /**
    * 短掩码转长掩码
    * @param mask
    * @return
    */
   public  static String toMask2(int mask){
      int first=0, i=0,mi = 0;
      if(mask==0){
         return "0:0:0:0:0:0:0:0";
      }else if(mask<=16){
         mi = 15;
         for( i=0;i<mask;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return Integer.toHexString(first)+":0:0:0:0:0:0:0";
      }else if(mask<=32){
         mi = 15;
         for(i=0;i<mask-16;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:"+Integer.toHexString(first)+":0:0:0:0:0:0";
      }else if(mask<=48){
         mi = 15;
         for(i=0;i<mask-32;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:ffff:"+Integer.toHexString(first)+":0:0:0:0:0";
      }else if(mask<=64){
         mi = 15;
         for(i=0;i<mask-48;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:ffff:ffff:"+Integer.toHexString(first)+":0:0:0:0";
      }
      else if(mask<=80){
         mi = 15;
         for(i=0;i<mask-64;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:ffff:ffff:ffff:"+Integer.toHexString(first)+":0:0:0";
      }
      else if(mask<=96){
         mi = 15;
         for(i=0;i<mask-80;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:ffff:ffff:ffff:ffff:"+Integer.toHexString(first)+":0:0";
      }else if(mask<=112){
         mi = 15;
         for(i=0;i<mask-96;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:ffff:ffff:ffff:ffff:ffff:"+Integer.toHexString(first)+":0";
      }else if(mask<=128){
         mi = 15;
         for(i=0;i<mask-112;i++){
            first +=Math.pow(2, mi);
            mi--;
         }
          return "ffff:ffff:ffff:ffff:ffff:ffff:ffff:"+Integer.toHexString(first);
      }else{
         throw new IndexOutOfBoundsException("mask范围 0-128");
      }
   }
   
   
   /**
    * 
    * @Title: getMaskByte  
    * @Description: (长掩码转短掩码)  
    * @param subNetMask
    * @return
    */
    public static int getMaskByte(String subNetMask) {
           int maskByte = 0;
           String[] subNetMaskArray = subNetMask.split("\\:");
           if (subNetMaskArray.length > 0) {
               for (int i = 0; i < subNetMaskArray.length; i++) {
                   if (ObjectUtils.isNotEmpty(subNetMaskArray[i])) {
                       String tempByte = subNetMaskArray[i];
                       int byteNum = getMask(tempByte);
                       maskByte += byteNum;
                   }
               }
           }
           return maskByte;
       }

       public static Integer getMask(String n) {
           switch (n) {
               case "ffff":
                   return 16;
               case "fffe":
                   return 15;
               case "fffc":
                   return 14;
               case "fff8":
                   return 13;
               case "fff0":
                   return 12;
               case "ffe0":
                   return 11;
               case "ffc0":
                   return 10;
               case "ff80":
                   return 9;
               case "ff00":
                   return 8;
               case "fe00":
                   return 7;
               case "fc00":
                   return 6;
               case "f800":
                   return 5;
               case "f000":
                   return 4;
               case "e000":
                   return 3;
               case "c000":
                   return 2;
               case "8000":
                   return 1;
               default:
                   return 0;
           }
       }
   

   
   
   
   
   public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
      if (address == null) {
         throw new RuntimeException("getNetworkPart doesn't accept null address");
      }
      byte[] array = address.getAddress();
      if (prefixLength < 0 || prefixLength > array.length * 8) {
         throw new RuntimeException("getNetworkPart - bad prefixLength");
      }
      int offset = prefixLength / 8;
      int reminder = prefixLength % 8;
      byte mask = (byte) (0xFF << (8 - reminder));
      if (offset < array.length)
         array[offset] = (byte) (array[offset] & mask);
      offset++;
      for (; offset < array.length; offset++) {
         array[offset] = 0;
      }
      InetAddress netPart = null;
      try {
         netPart = InetAddress.getByAddress(array);
      } catch (UnknownHostException e) {
         throw new RuntimeException("getNetworkPart error - " + e.toString());
      }
      return netPart;
   }

   public static InetAddress hexToInet6Address(String addrHexString) throws IllegalArgumentException {
      try {
         return numericToInetAddress(String.format("%s:%s:%s:%s:%s:%s:%s:%s", addrHexString.substring(0, 4),
               addrHexString.substring(4, 8), addrHexString.substring(8, 12), addrHexString.substring(12, 16),
               addrHexString.substring(16, 20), addrHexString.substring(20, 24), addrHexString.substring(24, 28),
               addrHexString.substring(28, 32)));
      } catch (Exception e) {
         throw new IllegalArgumentException(e);
      }
   }

   public static InetAddress numericToInetAddress(String addrString) throws UnknownHostException {
      return InetAddress.getByName(addrString);
   }

   public static boolean ping(String ip, long time) {
      boolean isReach = false;
      try {
         String cmd = "ping -c 1 " + " -w " + time + " " + ip;
         Process p = Runtime.getRuntime().exec(cmd);
         int status = p.waitFor();
         if (status == 0) {
            isReach = true;
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      return isReach;
   }
   /**
    * ipv6转数字
    * @param ipv6
    * @return
    */
   public static BigInteger ipv6toInt(String ipv6)
   {
 
      int compressIndex = ipv6.indexOf("::");
      if (compressIndex != -1)
      {
         String part1s = ipv6.substring(0, compressIndex);
         String part2s = ipv6.substring(compressIndex + 1);
         BigInteger part1 = ipv6toInt(part1s);
         BigInteger part2 = ipv6toInt(part2s);
         int part1hasDot = 0;
         char ch[] = part1s.toCharArray();
         for (char c : ch)
         {
            if (c == ':')
            {
               part1hasDot++;
            }
         }
         // ipv6 has most 7 dot
         return part1.shiftLeft(16 * (7 - part1hasDot )).add(part2);
      }
      String[] str = ipv6.split(":");
      BigInteger big = BigInteger.ZERO;
      for (int i = 0; i < str.length; i++)
      {
         //::1
         if (str[i].isEmpty())
         {
            str[i] = "0";
         }
         big = big.add(BigInteger.valueOf(Long.valueOf(str[i], 16))
                 .shiftLeft(16 * (str.length - i - 1)));
      }
      return big;
   }
   
   /**
    * 数字转ipv6
    * @param big
    * @return
    */
   public static String int2ipv6(BigInteger big)
   {
      String str = "";
      BigInteger ff = BigInteger.valueOf(0xffff);
      for (int i = 0; i < 8 ; i++)
      {
         str = big.and(ff).toString(16) + ":" + str;
         
         big = big.shiftRight(16);
      }
      //the last :
      str = str.substring(0, str.length() - 1);
      
      return str.replaceFirst("(^|:)(0+(:|$)){2,8}", "::");
   }
   
   public static void main(String[] args) throws UnknownHostException {
/*    BigInteger b =BigInteger.ZERO;
      BigInteger c =BigInteger.ZERO;
      c = c.add(BigInteger.valueOf(Long.valueOf(1)));
      System.out.println(b.add(BigInteger.valueOf(Long.valueOf(9999))).compareTo(c));
      */
   }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值