How can I convert IPV6 address to IPV4 address?

前端 未结 5 648
日久生厌
日久生厌 2020-11-28 15:15

I have application that uses IPv4 addresses (it stores them as long), so it only understands IPv4 addresses.

Is it possible to convert

5条回答
  •  有刺的猬
    2020-11-28 15:59

    The IPAddress Java library can accomplish what you are describing here.

    IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:

    IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]
    

    From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.

        if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
            IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
            byte ipv4Bytes[] = derivedIpv4Address.getBytes();
            ...
         }
    

    The javadoc is available at the link.

提交回复
热议问题