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

 
/**
 * 
 */
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;
    }

}

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值