java实现linux中现有ip和新增ip是否在一个网段内
时间: 2024-09-26 09:16:45 浏览: 39
Javascript 判断两个IP是否在同一网段实例代码
在Java中检查两个IP地址是否属于同一个网络段,通常涉及到网络地址的计算和比较。你可以通过IP地址的掩码(subnet mask)来判断它们是否在同一网络。下面是一个简单的步骤:
1. **获取IP地址和掩码(子网掩码)**: 对于给定的IPv4地址,你需要获取其对应的二进制形式,并计算出它的网络部分(包括前缀长度)和主机部分。
```java
import java.net.InetAddress;
import java.util.regex.Pattern;
public class IPUtils {
private static final Pattern IP_PATTERN = Pattern.compile("^([0-9]{1,3}\\.){3}[0-9]{1,3}$");
public static boolean isSameNetwork(String ip1, String ip2, String subnet) throws Exception {
if (!IP_PATTERN.matcher(ip1).matches() || !IP_PATTERN.matcher(ip2).matches()) {
throw new IllegalArgumentException("Invalid IP address format");
}
InetAddress addr1 = InetAddress.getByName(ip1);
InetAddress addr2 = InetAddress.getByName(ip2);
byte[] netmask = InetAddress.getByName(subnet).getHostAddress().getBytes();
int prefixLength = getPrefixLength(netmask);
byte[] network1 = addr1.getAddress();
byte[] network2 = addr2.getAddress();
for (int i = 0; i < prefixLength; i++) {
network1[i] &= netmask[i];
network2[i] &= netmask[i];
}
return Arrays.equals(network1, network2);
}
private static int getPrefixLength(byte[] netmask) {
int prefixLength = 0;
while (prefixLength < 32 && netmask[prefixLength] == 255) {
prefixLength++;
}
return prefixLength;
}
}
```
**如何使用:**
```java
String existingIp = "192.168.1.1";
String newIp = "192.168.1.2";
String subnet = "255.255.255.0"; // 或者其他子网掩码
try {
boolean inSameSegment = IPUtils.isSameNetwork(existingIp, newIp, subnet);
System.out.println(inSameSegment ? "两个IP在同一个网段" : "不在同一个网段");
} catch (IllegalArgumentException | UnknownHostException e) {
e.printStackTrace();
}
```
阅读全文