写一个安卓ipv4及ipv6的字符串,int值,byte数组互相转换的函数
时间: 2024-02-25 07:51:25 浏览: 146
ipv4和ipv6字符串转换成数字
4星 · 用户满意度95%
下面是一个可用的 Java 函数示例,可以实现 IPv4 和 IPv6 字符串、int 和 byte 数组之间的相互转换:
```java
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
public class IPConverter {
public static int bytesToInt(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();
}
public static byte[] intToBytes(int i) {
return ByteBuffer.allocate(Integer.SIZE / 8).putInt(i).array();
}
public static byte[] ipv4ToBytes(String ipv4) throws UnknownHostException {
InetAddress inetAddress = Inet4Address.getByName(ipv4);
return inetAddress.getAddress();
}
public static String bytesToIpv4(byte[] bytes) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByAddress(bytes);
if (inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
} else {
throw new UnknownHostException("the input bytes is not a IPv4 address");
}
}
public static byte[] ipv6ToBytes(String ipv6) throws UnknownHostException {
InetAddress inetAddress = Inet6Address.getByName(ipv6);
return inetAddress.getAddress();
}
public static String bytesToIpv6(byte[] bytes) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByAddress(bytes);
if (inetAddress instanceof Inet6Address) {
return inetAddress.getHostAddress();
} else {
throw new UnknownHostException("the input bytes is not a IPv6 address");
}
}
}
```
使用示例:
```java
String ipv4 = "192.168.0.1";
byte[] ipv4Bytes = IPConverter.ipv4ToBytes(ipv4);
int ipv4Int = IPConverter.bytesToInt(ipv4Bytes);
System.out.println("IPv4 to bytes: " + ipv4Bytes);
System.out.println("IPv4 to int: " + ipv4Int);
System.out.println("Bytes to IPv4: " + IPConverter.bytesToIpv4(ipv4Bytes));
String ipv6 = "fe80::1";
byte[] ipv6Bytes = IPConverter.ipv6ToBytes(ipv6);
System.out.println("IPv6 to bytes: " + ipv6Bytes);
System.out.println("Bytes to IPv6: " + IPConverter.bytesToIpv6(ipv6Bytes));
```
阅读全文