mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-05-13 17:36:54 -04:00
feat(new-tool): ipv4 address converter
This commit is contained in:
parent
8930e139b2
commit
28145e0ffe
5 changed files with 152 additions and 1 deletions
|
@ -0,0 +1,38 @@
|
|||
import _ from 'lodash';
|
||||
|
||||
export { ipv4ToInt, ipv4ToIpv6, isValidIpv4 };
|
||||
|
||||
function ipv4ToInt({ ip }: { ip: string }) {
|
||||
if (!isValidIpv4({ ip })) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return ip
|
||||
.trim()
|
||||
.split('.')
|
||||
.reduce((acc, part, index) => acc + Number(part) * Math.pow(256, 3 - index), 0);
|
||||
}
|
||||
|
||||
function ipv4ToIpv6({ ip, prefix = '0000:0000:0000:0000:0000:ffff:' }: { ip: string; prefix?: string }) {
|
||||
if (!isValidIpv4({ ip })) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return (
|
||||
prefix +
|
||||
_.chain(ip)
|
||||
.trim()
|
||||
.split('.')
|
||||
.map((part) => parseInt(part).toString(16).padStart(2, '0'))
|
||||
.chunk(2)
|
||||
.map((blocks) => blocks.join(''))
|
||||
.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);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue