package org.kne.cloud.network.ipv6; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Objects; import java.util.UUID; public class IPv6AddressGroup implements Comparable{ public IPv6AddressGroup(IPv6Address address) { this(address, 128); } @Override public String toString() { return address+"/"+prefixLength; } @Override public int hashCode() { return Objects.hash(address, prefixLength); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IPv6AddressGroup other = (IPv6AddressGroup) obj; return Objects.equals(address, other.address) && prefixLength == other.prefixLength; } public IPv6AddressGroup(IPv6Address address, int prefixLength) { super(); this.address = address; this.prefixLength = prefixLength; } public IPv6AddressGroup(DataInputStream in) throws IOException { readFromStream(in); } private IPv6Address address; private int prefixLength=128; public IPv6Address getAddress() { return address; } public int getPrefixLength() { return prefixLength; } @Override public int compareTo(IPv6AddressGroup o) { return -Integer.compare(prefixLength, o.prefixLength); } public void writeToStream(DataOutputStream out) throws IOException { out.writeLong(address.getHigh()); out.writeLong(address.getLow()); out.write(prefixLength); } public void readFromStream(DataInputStream in) throws IOException { long high=in.readLong(); long low=in.readLong(); address=new IPv6Address(high,low); prefixLength=in.read(); } public boolean checkMatch(IPv6Address address2) { IPv6Address cmsk= IPv6Address.createMask(prefixLength); return address2.maskWith(cmsk).equals(address.maskWith(cmsk)); } /** * 返回裁剪后的路由表地址(主机位清零)。 * 例如 2001:db8:1::100/64 → 2001:db8:1::/64 */ public IPv6AddressGroup toNetworkRoute() { IPv6Address mask = IPv6Address.createMask(prefixLength); IPv6Address maskedAddr = address.maskWith(mask); return new IPv6AddressGroup(maskedAddr, prefixLength); } }