1.输入验证:判定是否为IPv4地址或范围.
import validator from 'validator'
import { isEmpty, trim, split } from 'lodash'
export function isIpOrIpRange(str, version = 4) {
if (isEmpty(str) || isEmpty(trim(str))) {
return false
}
if (validator.isIP(str, version) || validator.isIPRange(str, version)) {
return true
}
const arr = split(str, '-')
return (
arr.length === 2 &&
validator.isIP(arr[0], version) &&
validator.isIP(arr[1], version) &&
ipv4ToNumber(arr[0]) <= ipv4ToNumber(arr[1])
)
}
export function ipv4ToNumber(ip) {
if (!ip || !validator.isIP(ip, 4)) {
throw new Error('无效的IPv4地址')
}
var result = 0
ip.split('.').forEach(function(octet) {
result <<= 8
result += parseInt(octet)
})
return result >>> 0
}
export function validIps(value) {
const values = value.includes('\n') ? value.replace(/\n|\r\n/g, ',') : value
const ipv4s = values.split(',')
for (let item of ipv4s) {
const valid = isIpOrIpRange(item)
if (!valid) {
return false
}
}
return true
}