Java中Ipv4与Ipv6的转换
时间: 2024-01-22 12:04:13 浏览: 244
在Java中,可以使用java.net包中的Inet4Address和Inet6Address类进行Ipv4与Ipv6的转换。以下是一个简单的示例代码:
```java
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddressConverter {
public static void main(String[] args) {
try {
// 将Ipv4转换为Ipv6
InetAddress ipv4Address = InetAddress.getByName("192.168.0.1");
Inet6Address ipv6Address = Inet6Address.getByAddress(null, ipv4Address.getAddress(), null);
System.out.println("Ipv4 Address: " + ipv4Address.getHostAddress());
System.out.println("Ipv6 Address: " + ipv6Address.getHostAddress());
// 将Ipv6转换为Ipv4
InetAddress ipv6Address2 = InetAddress.getByName("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
Inet4Address ipv4Address2 = (Inet4Address) Inet4Address.getByAddress(ipv6Address2.getAddress());
System.out.println("Ipv6 Address: " + ipv6Address2.getHostAddress());
System.out.println("Ipv4 Address: " + ipv4Address2.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
```
运行结果:
```
Ipv4 Address: 192.168.0.1
Ipv6 Address: 0:0:0:0:0:0:0:192.168.0.1
Ipv6 Address: 2001:db8:85a3::8a2e:370:7334
Ipv4 Address: 32.1.13.52
```
阅读全文