把IP地址转化为int类型

public class IPv4Util {

/**
     * 把IP地址转化为int
     * @param ipAddr
     * @return int
     */
   
    public static long ipToInt(String ipAddr) {
        try {
        String[] ipArr = ipAddr.split("\\.");
        StringBuffer sb =new StringBuffer();
            for(int i=0;i<ipArr.length;i++){
            int a = Integer.valueOf(ipArr[i]);
            String a16 = "";
            if(a<16){
            a16 = String.valueOf(0)+get16(a);
            }else{
            a16 = get16(a);
            }
            sb.append(a16);
            }
            if(get10(sb.toString()) <= 0){
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
            }
            return get10(sb.toString());
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }
    }
   
    /**
     * 十进制转十六进制
     * @param x
     * @return
     */
    public static String get16(int x){
    return Integer.toHexString(x);
    }
   
    public static long get10(String s){
    Long l=Long.parseLong(s, 16);
    return l;
    //return Integer.parseInt(s, 16);
    }
   
}

猜你喜欢

转载自pange.iteye.com/blog/2330162