-
Notifications
You must be signed in to change notification settings - Fork 1
Convert IPV6 to IPV4 if possible
Tutik Alexsandr edited this page Apr 1, 2024
·
2 revisions
By default uwebsockets.js returns the client's IP in ipv6 format This small piece of code will allow you to get IPV4 from IPV6
helper/ip.js
const parseIpv6 = (ip6str) => {
const str = ip6str.toString();
const ar = [];
for (var i = 0; i < 8; i++) ar[i] = 0;
if (str === '::') return ar;
const sar = str.split(':');
let slen = sar.length;
if (slen > 8) slen = 8;
let j = 0;
i = 0
for (i = 0; i < slen; i++) {
if (i && sar[i] === '') {
j = 9 - slen + i;
continue;
}
ar[j] = parseInt(`0x0${sar[i]}`);
j++;
}
return ar;
}
exports.convertIpv6toIpv4 = function(ip, force = false) {
if (this.isValidIpv4(ip)){
return ip;
}
if (force === true || /0000:0000:0000:0000:0000:/.test(ip)) {
const ip6parsed = parseIpv6(ip);
return `${ip6parsed[6] >> 8}.${ip6parsed[6] & 0xff}.${ip6parsed[7] >> 8}.${ip6parsed[7] & 0xff}`;
}
return ip;
}
exports.isValidIpv4 = function (ip) {
let ipv4_pattern = /^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/;
if (!ipv4_pattern.test(ip)) {
return false;
}
let token = ip.split('.');
return (
token[0] <= 255 && token[1] <= 255 && token[2] <= 255 && token[3] <= 255
);
};
exports.isValidIpv6 = function (ip) {
let ipv6_pattern = /^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/;
return ipv6_pattern.test(ip);
};
exports.isValidIp = function (ip) {
return this.isValidIpv4(ip) || this.isValidIpv6(ip);
};