java 简单实现ip地址与十进制的转换
时间: 2023-07-16 17:12:15 浏览: 112
可以使用 `InetAddress` 类来实现 IP 地址与十进制的转换。
将 IP 地址转为十进制:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IpToDecimal {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("192.168.0.1");
byte[] bytes = address.getAddress();
int result = 0;
for (byte b : bytes) {
result = result << 8 | (b & 0xFF);
}
System.out.println(result);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
```
将十进制转为 IP 地址:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class DecimalToIp {
public static void main(String[] args) {
int decimal = 3232235521;
byte[] bytes = new byte[]{
(byte) ((decimal >> 24) & 0xFF),
(byte) ((decimal >> 16) & 0xFF),
(byte) ((decimal >> 8) & 0xFF),
(byte) (decimal & 0xFF)
};
try {
InetAddress address = InetAddress.getByAddress(bytes);
System.out.println(address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
```
阅读全文