java实现ipv4和ipv6字符串地址与数字类型的转换

项目中需要将IPv4或IPv6地址转换成数字类型,或者将数字类型的ip地址转换成字符串的IPv4或IPv6地址。所以需要一个工具类,这篇文章记录一下自己使用的工具类。

IpUtil.java


import java.math.BigInteger;

public class IpUtil {

    /**ipv4字符串转为long
     *
     */
    public static long ipToLong(String ipv4){
        String[] splits = ipv4.split("\\.");
        long l = 0;
        l = l + (Long.valueOf(splits[0], 10)) << 24;
        l = l + (Long.valueOf(splits[1], 10)) << 16;
        l = l + (Long.valueOf(splits[2], 10)) << 8;
        l = l + (Long.valueOf(splits[3], 10));
        return l;
    }

    /**long转为ipv4字符串
     *
     */
    public static String longToIp(long l){
        String ip = "";
        ip = ip + (l >>> 24);
        ip = ip + "." +((0x00ffffff & l) >>> 16);
        ip = ip + "." +((0x0000ffff & l) >>> 8);
        ip = ip + "." +(0x000000ff & l);
        return ip;
    }

    /**ipv6字符串转BigInteger数
     *
     */
    public static BigInteger ipv6ToInt(String ipv6){
        int compressIndex = ipv6.indexOf("::");
        if (compressIndex != -1){
            String part1s = ipv6.substring(0, compressIndex);
            String part2s = ipv6.substring(compressIndex + 1);
            BigInteger part1 = ipv6ToInt(part1s);
            BigInteger part2 = ipv6ToInt(part2s);
            int part1hasDot = 0;
            char ch[] = part1s.toCharArray();
            for(char c : ch){
                if(c == ':'){
                    part1hasDot++;
                }
            }
            return part1.shiftLeft(16 * (7 - part1hasDot)).add(part2);
        }
        String[] str = ipv6.split(":");
        BigInteger big = BigInteger.ZERO;
        for(int i = 0; i < str.length; i++){
            //::1
            if(str[i].isEmpty()){
                str[i] = "0";
            }
            big = big.add(BigInteger.valueOf(Long.valueOf(str[i], 16)).shiftLeft(16 * (str.length - i - 1)));
        }
        return big;
    }

    /**BigInteger数 转为ipv6字符串
     *
     */
    public static String intToIpv6(BigInteger big){
        String str = "";
        BigInteger ff = BigInteger.valueOf(0xffff);
        for (int i = 0; i < 8; i++){
            str = big.and(ff).toString(16) + ":" + str;
            big = big.shiftRight(16);
        }
        //去掉最后的:号
        str = str.substring(0, str.length() - 1);
        return str.replaceFirst("(^|:)(0+(:|$)){2,8}", "::");
    } 

    /**将精简的ipv6地址扩展为全长度的ipv6地址
     *
     */
    public static String completeIpv6(String strIpv6){
        BigInteger big = ipv6ToInt(strIpv6);
        String str = big.toString(16);
        String completeIpv6Str = "";
        while(str.length() != 32){
            str = "0" + str;
        }
        for (int i = 0; i <= str.length(); i += 4){
            completeIpv6Str += str.substring(i, i + 4);
            if ((i + 4) == str.length()){
                break;
            }
            completeIpv6Str += ":";
        }
        return completeIpv6Str;
    } 
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个可用的 Java 函数示例,可以实现 IPv4IPv6 字符串、int 和 byte 数组之间的相互转换: ```java import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; public class IPConverter { public static int bytesToInt(byte[] bytes) { return ByteBuffer.wrap(bytes).getInt(); } public static byte[] intToBytes(int i) { return ByteBuffer.allocate(Integer.SIZE / 8).putInt(i).array(); } public static byte[] ipv4ToBytes(String ipv4) throws UnknownHostException { InetAddress inetAddress = Inet4Address.getByName(ipv4); return inetAddress.getAddress(); } public static String bytesToIpv4(byte[] bytes) throws UnknownHostException { InetAddress inetAddress = InetAddress.getByAddress(bytes); if (inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } else { throw new UnknownHostException("the input bytes is not a IPv4 address"); } } public static byte[] ipv6ToBytes(String ipv6) throws UnknownHostException { InetAddress inetAddress = Inet6Address.getByName(ipv6); return inetAddress.getAddress(); } public static String bytesToIpv6(byte[] bytes) throws UnknownHostException { InetAddress inetAddress = InetAddress.getByAddress(bytes); if (inetAddress instanceof Inet6Address) { return inetAddress.getHostAddress(); } else { throw new UnknownHostException("the input bytes is not a IPv6 address"); } } } ``` 使用示例: ```java String ipv4 = "192.168.0.1"; byte[] ipv4Bytes = IPConverter.ipv4ToBytes(ipv4); int ipv4Int = IPConverter.bytesToInt(ipv4Bytes); System.out.println("IPv4 to bytes: " + ipv4Bytes); System.out.println("IPv4 to int: " + ipv4Int); System.out.println("Bytes to IPv4: " + IPConverter.bytesToIpv4(ipv4Bytes)); String ipv6 = "fe80::1"; byte[] ipv6Bytes = IPConverter.ipv6ToBytes(ipv6); System.out.println("IPv6 to bytes: " + ipv6Bytes); System.out.println("Bytes to IPv6: " + IPConverter.bytesToIpv6(ipv6Bytes)); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值