java判断ip是否在同一个网段
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IpRangeChecker {
//判断的具体方法
public static boolean isIpInRange(String ip, String startIp, String endIp) throws UnknownHostException {
long ipLong = ipToLong(ip);
long startIpLong = ipToLong(startIp);
long endIpLong = ipToLong(endIp);
return (ipLong >= startIpLong && ipLong <= endIpLong);
}
//把ip字符串转为long
private static long ipToLong(String ip) throws UnknownHostException {
InetAddress ipAddress = InetAddress.getByName(ip);
byte[] bytes = ipAddress.getAddress();
long result = 0;
for (byte b : bytes) {
//把小段的地址左移8位数
result <<= 8;
//前端地址的值*256再相加后面的地址值
result |= b & 0xFF;
}
return result;
}
}
使用方法:
String ip = "192.168.1.1";
String startIp = "192.168.1.0";
String endIp = "192.168.1.254";
boolean result = IpRangeChecker.isIpInRange(ip, startIp, endIp);
if (result) {
System.out.println("IP地址在指定的网段内");
} else {
System.out.println("IP地址不在指定的网段内");
}