v4
@nat.vg · 1mo ago · javascript · 51 loc · raw · 0 comments
1/**2 * Extracts /48, /56, and /64 prefixes from an IPv6 address3 * @param {string} ipv6 - The IPv6 address in standard or compressed format4 * @returns {Object} Object containing the /48, /56, and /64 prefixes5 */6function extractIPv6Prefixes(ipv6) {7 // Expand the compressed IPv6 address8 let expandedIPv6 = expandIPv6(ipv6);9 10 // Split the address into groups11 const groups = expandedIPv6.split(':');12 13 // Extract prefixes14 const prefix48 = groups.slice(0, 3).join(':');15 const prefix56 = groups.slice(0, 3).join(':') + ':' + groups[3].substring(0, 1);16 const prefix64 = groups.slice(0, 4).join(':');17 18 return {19 prefix48: prefix48,20 prefix56: prefix56,21 prefix64: prefix64,22 expanded: expandedIPv623 };24}2526/**27 * Expands a compressed IPv6 address to its full form28 * @param {string} ipv6 - The IPv6 address, possibly in compressed format29 * @returns {string} The expanded IPv6 address30 */31function expandIPv6(ipv6) {32 // Handle double colon expansion33 if (ipv6.includes('::')) {34 const parts = ipv6.split('::');35 const left = parts[0] ? parts[0].split(':') : [];36 const right = parts[1] ? parts[1].split(':') : [];37 const missing = 8 - left.length - right.length;38 39 // Create the expanded middle section40 const middle = Array(missing).fill('0000');41 42 // Join all parts together43 const full = [...left, ...middle, ...right];44 45 // Ensure each part is properly padded46 return full.map(part => part.padStart(4, '0')).join(':');47 }48 49 // If no compression, just ensure each part is padded50 return ipv6.split(':').map(part => part.padStart(4, '0')).join(':');51}
login to post a comment