Java按位或合併ipv6字首和字尾

Jackie_JK發表於2024-12-07

在某些情況下只能獲取到ipv6的字首和字尾,在合併時需要按位或,可以使用本文的程式碼。

示例版本

<dependency>
	<groupId>com.github.seancfoley</groupId>
	<artifactId>ipaddress</artifactId>
	<version>5.5.1</version>
</dependency>

實現:

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Ipv6MergeUtil {

  public static String merge(String framedIpv6Prefix, String framedInterfaceId) {
    if (framedIpv6Prefix == null || framedInterfaceId == null) {
      return null;
    }
    try {
      IPAddressString prefix = new IPAddressString(framedIpv6Prefix);
      IPAddressString id = new IPAddressString("::" + framedInterfaceId);
      IPAddress prefixAddress = prefix.getAddress();
      IPAddress idAddress = id.getAddress();
      if (prefixAddress != null && idAddress != null) {
        return idAddress.bitwiseOr(prefixAddress).toString();
      }
    } catch (Exception e) {
      //do nothing
    }
    return framedInterfaceId;
  }

}

相關文章