Validate IP Address
Description
doc
Solutions
First Idea
function isIPv4(ip) {
const digits = ip.split('.')
if (digits.length !== 4) {
return false
}
if (digits.some((v) => v.length < 1 || (v.length > 1 && v[0] === '0'))) {
return false
}
if (digits.some((v) => !/^[\d]*$/.test(v))) {
return false
}
if (
digits.map((v) => parseInt(v)).some((v) => isNaN(v) || v < 0 || v > 255)
) {
return false
}
return true
}
function isIPv6(ip) {
const digits = ip.split(':')
if (digits.length !== 8) {
return false
}
if (digits.some((v) => v.length < 1 || v.length > 4)) {
return false
}
if (digits.some((v) => !/^[\da-fA-F]*$/.test(v))) {
return false
}
if (digits.some((v) => isNaN(parseInt(v, 16)))) {
return false
}
return true
}
/**
* @param {string} queryIP
* @return {string}
*/
var validIPAddress = function (queryIP) {
if (isIPv4(queryIP)) {
return 'IPv4'
}
if (isIPv6(queryIP)) {
return 'IPv6'
}
return 'Neither'
}