将点分式的IP地址转换成长整型

来源:互联网 发布:oa免费办公软件 编辑:程序博客网 时间:2024/05/17 02:59
 
/** *  */package test;import java.net.InetAddress;import java.net.UnknownHostException;import java.nio.ByteBuffer;/** * @author wKF46214 *  */public class IpConvert{    /**     * @param args     */    public static void main(String[] args)    {        try        {            long ip1 = convertIpFromString2Long("1.1.1.1");            long ip2 = convertIpFromString2Long("255.255.255.255");            System.out.println(ip1);            System.out.println(ip2);            long a = 3294967295L;            String ip3 = convertIpFromLong2String(a);            System.out.println(ip3);        }        catch (UnknownHostException e)        {            e.printStackTrace();        }    }    /**     * 将点分式的IP地址转换成长整型     * @param ip     * @return     * @throws UnknownHostException     */    public static long convertIpFromString2Long(String ip) throws UnknownHostException    {        if (ip == null || ip.equals(""))        {            return 0;        }        InetAddress ipaddr = InetAddress.getByName(ip);        byte[] bas = ipaddr.getAddress();        int result = 0;        result |= ((short) (bas[0] & 0x00ff) << 24);        result |= ((short) (bas[1] & 0x00ff) << 16);        result |= ((short) (bas[2] & 0x00ff) << 8);        result |= (short) (bas[3] & 0x00ff);        return convertUnsignedInt2Long(result);    }    public static long convertUnsignedInt2Long(int value)    {        long ret;        ret = value >>> 1;        ret <<= 1;        ret |= (value << 31) >>> 31;        return ret;    }    /**     * 将长整型的IP地址转换成点分式     *      * @param ip     * @return     * @throws UnknownHostException     */    public static String convertIpFromLong2String(long ip) throws UnknownHostException    {        if (ip <= 0)        {            return "";        }        ByteBuffer buf = ByteBuffer.allocate(4);        // buf.order(ByteOrder.LITTLE_ENDIAN);//必须转换成小头序,才能正确显示IP        buf.putInt(convertLong2UnsignedInt(ip));        InetAddress addr = InetAddress.getByAddress(buf.array());        return addr.getHostAddress();    }    public static int convertLong2UnsignedInt(long value)    {        int ret;        ret = (int) (value & 0x00000000ffffffff);        return ret;    }}