2023-04-08 21:10:00 +02:00
|
|
|
import _ from 'lodash';
|
|
|
|
|
|
|
|
export { ipv4ToInt, ipv4ToIpv6, isValidIpv4 };
|
|
|
|
|
|
|
|
function ipv4ToInt({ ip }: { ip: string }) {
|
|
|
|
if (!isValidIpv4({ ip })) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
return ip
|
|
|
|
.trim()
|
|
|
|
.split('.')
|
2023-05-28 23:13:24 +02:00
|
|
|
.reduce((acc, part, index) => acc + Number(part) * 256 ** (3 - index), 0);
|
2023-04-08 21:10:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function ipv4ToIpv6({ ip, prefix = '0000:0000:0000:0000:0000:ffff:' }: { ip: string; prefix?: string }) {
|
|
|
|
if (!isValidIpv4({ ip })) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
2023-05-28 23:13:24 +02:00
|
|
|
prefix
|
|
|
|
+ _.chain(ip)
|
2023-04-08 21:10:00 +02:00
|
|
|
.trim()
|
|
|
|
.split('.')
|
2023-08-21 18:27:08 +00:00
|
|
|
.map(part => Number.parseInt(part).toString(16).padStart(2, '0'))
|
2023-04-08 21:10:00 +02:00
|
|
|
.chunk(2)
|
2023-05-28 23:13:24 +02:00
|
|
|
.map(blocks => blocks.join(''))
|
2023-04-08 21:10:00 +02:00
|
|
|
.join(':')
|
|
|
|
.value()
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
function isValidIpv4({ ip }: { ip: string }) {
|
|
|
|
const cleanIp = ip.trim();
|
|
|
|
|
|
|
|
return /^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$/.test(cleanIp);
|
|
|
|
}
|