简体   繁体   中英

How to validate an array of bytes as ipv6 address?

Background: When validating a string as a valid ipv6 address there are a lot of scenarios to take into account because of abbreviations.

::
::1
2622:ca00:139:594::64:90f3
2622:ca00:0139:0594:0000:0000:0064:90f3

are all valid ways to represent ipv6 addresses as strings. If I needed a function to validate a string as a valid ipv6 address, I would need to take all of these cases into account.

Problem: I need help writing a java/scala function that takes in an array of bytes and validates it as an ipv6 address. What I cant seem to find out is when an ipv6 address is written as an array of bytes, is it always 16 bytes long or are there ways to abbreviate similar to how addresses can be abbreviated with string notation? If the byte representation of an ipv6 is always 16 bytes and never abbreviated I believe I can just test for valid ipv6 with the below logic - is that the case?

  /**
   * Return true if byte array is a valid ipv6 address.
   *
   * @param ip - array of bytes representing ip address
   * @return - true if ip address is a valid ipv6 address
   */
  def isIpV6(ip: Array[Byte]): Boolean = {
    ip != null && ip.length == 16
  }

There are complicated possibilites for parsing that, if you really have to do that without the help of a library. It will not fit on one page.

The most comfortable way is InetAddress.getByName() which will throw an exception if something is wrong.

Guava has a similar method that is for IPs only .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM