欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IP地址与数字相互转换

程序员文章站 2022-06-03 17:42:30
...
/**  
     * ip地址转成整数.  
     * @param ip  
     * @return  
     */  
    public static long ip2long(String ip) {   
        String[] ips = ip.split("[.]");   
        long num =  16777216L*Long.parseLong(ips[0]) + 65536L*Long.parseLong(ips[1]) + 256*Long.parseLong(ips[2]) + Long.parseLong(ips[3]);   
        return num;   
    }   
       
    /**  
     * 整数转成ip地址.  
     * @param ipLong  
     * @return  
     */  
    public static String long2ip(long ipLong) {   
        //long ipLong = 1037591503;   
        long mask[] = {0x000000FF,0x0000FF00,0x00FF0000,0xFF000000};   
        long num = 0;   
        StringBuffer ipInfo = new StringBuffer();   
        for(int i=0;i<4;i++){   
            num = (ipLong & mask[i])>>(i*8);   
            if(i>0) ipInfo.insert(0,".");   
            ipInfo.insert(0,Long.toString(num,10));   
        }   
        return ipInfo.toString();   
    }  

 

相关标签: ip