ip-int-byte[]互转-使用java原生api

近来需要存储ip,看网上的代码都是long类型的,占用空间过大,直接查看了jdk的源码,发现自带了这些功能,废话不多说,直接上代码,自己看

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IpV4Util {
    /**
     * 将ip转为int
     * @param ip
     * @return int可能为负数
     * @throws UnknownHostException
     */
    public static int ipToInt(String ip) throws UnknownHostException {
        byte[] addr = ipToBytes(ip);
        //reference  java.net.Inet4Address.Inet4Address
        int address  = addr[3] & 0xFF;
        address |= ((addr[2] << 8) & 0xFF00);
        address |= ((addr[1] << 16) & 0xFF0000);
        address |= ((addr[0] << 24) & 0xFF000000);
        return address;
    }

    /**
     * 将ip转为int
     * @param ip
     * @return xxx.xxx.xxx.xxx
     */
    public static String intToIp(int ip) {
        byte[] addr = new byte[4];
        addr[0] = (byte) ((ip >>> 24) & 0xFF);
        addr[1] = (byte) ((ip >>> 16) & 0xFF);
        addr[2] = (byte) ((ip >>> 8) & 0xFF);
        addr[3] = (byte) (ip & 0xFF);
        return bytesToIp(addr);
    }

    /**
     * 将byte数组转为ip字符串
     * @param src
     * @return xxx.xxx.xxx.xxx
     */
    public static String bytesToIp(byte[] src) {
        return (src[0] & 0xff) + "." + (src[1] & 0xff) + "." + (src[2] & 0xff)
                + "." + (src[3] & 0xff);
    }

    /**
     * 将ip字符串转为byte数组,注意:ip不可以是域名,否则会进行域名解析
     * @param ip
     * @return byte[]
     * @throws UnknownHostException
     */
    public static byte[] ipToBytes(String ip) throws UnknownHostException {
        return InetAddress.getByName(ip).getAddress();
    }

    public static void main(String[] args) throws UnknownHostException {
        String ip = "255.255.255.123";
        int ipI = ipToInt(ip);
        System.out.println(ip+"->"+ipI);
        System.out.println(ipI+"->"+intToIp(ipI));
        byte[] bytes = ipToBytes(ip);
        System.out.println(ip+"->bytes.length="+bytes.length);
        System.out.println("bytes->"+bytesToIp(bytes));
    }
}
输出结果:
255.255.255.123->-133
-133->255.255.255.123
255.255.255.123->bytes.length=4
bytes->255.255.255.123
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值