以下是一个Java IPv6工具类的示例代码,它包含了各种IPv6地址相关的操作和转换方法,可以方便地处理IPv6地址:
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPv6Utils {
// 将IPv6地址字符串转换为InetAddress对象
public static InetAddress toInetAddress(String ipv6Str) throws UnknownHostException {
return Inet6Address.getByName(ipv6Str);
// 将InetAddress对象转换为IPv6地址字符串
public static String toIPv6String(InetAddress inetAddress) {
if (inetAddress instanceof Inet6Address) {
return inetAddress.getHostAddress();
} else {
throw new IllegalArgumentException("Not an IPv6 address");
// 检查是否为IPv6地址
public static boolean isIPv6Address(String ipAddress) {
try {
InetAddress.getByName(ipAddress);
return true;
} catch (UnknownHostException e) {
return false;
// 检查是否为IPv4-mapped IPv6地址
public static boolean isIPv4MappedAddress(String ipAddress) {
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
return inetAddress instanceof Inet6Address && ((Inet6Address)inetAddress).isIPv4MappedAddress();
} catch (UnknownHostException e) {
return false;
// 将IPv4地址转换为IPv6地址
public static String toIPv6Address(String ipv4Address) {
String[] octets = ipv4Address.split("\\.");
byte[] octetBytes = new byte[4];
for (int i = 0; i < octets.length; i++) {
octetBytes[i] = (byte) Integer.parseInt(octets[i]);
byte[] ipv6Bytes = new byte[16];
ipv6Bytes[10] = (byte)0xff;
ipv6Bytes[11] = (byte)0xff;
ipv6Bytes[12] = octetBytes[0];
ipv6Bytes[13] = octetBytes[1];
ipv6Bytes[14] = octetBytes[2];
ipv6Bytes[15] = octetBytes[3];
try {
return InetAddress.getByAddress(ipv6Bytes).getHostAddress();
} catch (UnknownHostException e) {
return null;
这个工具类包含了常见的IPv6地址转换和操作方法,包括将IPv6地址字符串转换为InetAddress对象、将InetAddress对象转换为IPv6地址字符串、检查是否为IPv6地址、检查是否为IPv4-mapped IPv6地址、将IPv4地址转换为IPv6地址等。
使用这个工具类,您可以方便地处理IPv6地址,而无需自己编写复杂的代码。