java 根据当前ip,获取上一个ip和下一个ip
时间: 2023-10-30 21:06:11 浏览: 83
java获取ip地址
Java中可以使用`InetAddress`类来获取当前IP地址,然后通过位运算来计算上一个IP地址和下一个IP地址。
下面是一个示例代码:
```java
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPUtil {
public static String getPreviousIP(String ip) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(ip);
byte[] address = inetAddress.getAddress();
int intValue = ((address[3] & 0xFF) << 24) |
((address[2] & 0xFF) << 16) |
((address[1] & 0xFF) << 8) |
(address[0] & 0xFF);
intValue--;
byte[] result = new byte[4];
result[0] = (byte) (intValue & 0xFF);
result[1] = (byte) ((intValue >> 8) & 0xFF);
result[2] = (byte) ((intValue >> 16) & 0xFF);
result[3] = (byte) ((intValue >> 24) & 0xFF);
return InetAddress.getByAddress(result).getHostAddress();
}
public static String getNextIP(String ip) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getByName(ip);
byte[] address = inetAddress.getAddress();
int intValue = ((address[3] & 0xFF) << 24) |
((address[2] & 0xFF) << 16) |
((address[1] & 0xFF) << 8) |
(address[0] & 0xFF);
intValue++;
byte[] result = new byte[4];
result[0] = (byte) (intValue & 0xFF);
result[1] = (byte) ((intValue >> 8) & 0xFF);
result[2] = (byte) ((intValue >> 16) & 0xFF);
result[3] = (byte) ((intValue >> 24) & 0xFF);
return InetAddress.getByAddress(result).getHostAddress();
}
}
```
使用方法:
```java
String currentIP = "192.168.1.100";
String previousIP = IPUtil.getPreviousIP(currentIP);
String nextIP = IPUtil.getNextIP(currentIP);
System.out.println("Previous IP: " + previousIP);
System.out.println("Next IP: " + nextIP);
```
输出结果:
```
Previous IP: 192.168.1.99
Next IP: 192.168.1.101
```
阅读全文