35 lines
No EOL
1.4 KiB
TypeScript
35 lines
No EOL
1.4 KiB
TypeScript
export const validateIPAddress = (ip: string) => {
|
|
const ipv4Pattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
|
|
const ipv6Pattern = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
|
|
return ipv4Pattern.test(ip) || ipv6Pattern.test(ip);
|
|
};
|
|
|
|
export const validateSameSubnet = (ip1: string, ip2: string, ip3: string | string[]): boolean => {
|
|
const extractSubnet = (ip: string): string => {
|
|
if (typeof ip !== 'string') {
|
|
throw new TypeError(`Некорректный формат IP-адреса: ${ip}`);
|
|
}
|
|
return ip.split('.').slice(0, 3).join('.');
|
|
};
|
|
|
|
const areInSameSubnet = (ip: string, subnet: string): boolean => {
|
|
return extractSubnet(ip) === subnet;
|
|
};
|
|
|
|
try {
|
|
const subnet1 = extractSubnet(ip1);
|
|
const subnet2 = extractSubnet(ip2);
|
|
|
|
// Проверяем, что IP и шлюз в одной подсети
|
|
if (subnet1 !== subnet2) {
|
|
return false;
|
|
}
|
|
|
|
// Если DNS — массив, проверяем, что хотя бы один DNS в той же подсети
|
|
const dnsArray = Array.isArray(ip3) ? ip3 : [ip3];
|
|
return dnsArray.some(dns => areInSameSubnet(dns, subnet1));
|
|
} catch (error) {
|
|
console.error(error);
|
|
return false;
|
|
}
|
|
}; |