为了下次找的方便,写个文章记录下 ip起始地址
function getLowAddr (ip, netMask) {
let lowAddr = '';
const ipArray = [];
const netMaskArray = [];
if (ip.split('.').length !== 4 || netMask === '') {
return '';
}
for (let i = 0; i < 4; i += 1) {
ipArray[i] = Number(ip.split('.')[i]);
netMaskArray[i] = netMask.split('.')[i];
if (
Number(ipArray[i]) > 255 ||
Number(ipArray[i]) < 0 ||
(Number(netMaskArray[i]) > 255 && Number(netMaskArray[i]) < 0)
) {
return '';
}
ipArray[i] = Number(ipArray[i]) & Number(netMaskArray[i]);
}
for (let i = 0; i < 4; i += 1) {
if (i === 3) {
ipArray[i] = Number(ipArray[i]) + 1;
}
if (lowAddr === '') {
lowAddr += ipArray[i];
} else {
lowAddr += `.${ipArray[i]}`;
}
}
return lowAddr;
}
ip结束地址
function getHighAddr (ip, netMask) {
let lowAddr = getLowAddr(ip, netMask);
let hostNumber = getHostNumber(netMask);
if ('' === lowAddr || hostNumber === 0) {
return '';
}
let lowAddrArray = [];
for (let i = 0; i < 4; i += 1) {
lowAddrArray[i] = Number(lowAddr.split('.')[i]);
if (i === 3) {
lowAddrArray[i] = Number(lowAddrArray[i]) - 1;
}
}
lowAddrArray[3] = lowAddrArray[3] + Number(hostNumber - 1);
if (lowAddrArray[3] > 255) {
let k = parseInt(String(lowAddrArray[3] / 256), 10);
lowAddrArray[3] = lowAddrArray[3] % 256;
lowAddrArray[2] = Number(lowAddrArray[2]) + Number(k);
if (lowAddrArray[2] > 255) {
k = parseInt(String(lowAddrArray[2] / 256), 10);
lowAddrArray[2] = lowAddrArray[2] % 256;
lowAddrArray[1] = Number(lowAddrArray[1]) + Number(k);
if (lowAddrArray[1] > 255) {
k = parseInt(String(lowAddrArray[1] / 256), 10);
lowAddrArray[1] = lowAddrArray[1] % 256;
lowAddrArray[0] = Number(lowAddrArray[0]) + Number(k);
}
}
}
let highAddr = '';
for (let i = 0; i < 4; i += 1) {
if (i === 3) {
lowAddrArray[i] -= 1;
}
if ('' === highAddr) {
highAddr = String(lowAddrArray[i]);
} else {
highAddr += '.' + lowAddrArray[i];
}
}
return highAddr;
}
获取主机数
function getHostNumber(netMask) {
let hostNumber = 0;
const netMaskArray = [];
for (let i = 0; i < 4; i += 1) {
netMaskArray[i] = netMask.split('.')[i];
if (Number(netMaskArray[i]) < 255) {
hostNumber = 256 ** (3 - i) * (256 - Number(netMaskArray[i]));
break;
}
}
return hostNumber;
}
转换掩码的格式
function getNetMask(inetMask) {
let netMask = '';
if (inetMask > 32) {
return netMask;
}
const num1 = parseInt(`${inetMask / 8}`, 2);
let num2 = inetMask % 8;
const array = [];
for (let i = 0; i < num1; i += 1) {
array[i] = 255;
}
for (let i = num1; i < 4; i += 1) {
array[i] = 0;
}
for (let i = 0; i < num2; num2 -= 1) {
array[num1] += 2 ** (8 - num2);
}
netMask = `${array[0]}.${array[1]}.${array[2]}.${array[3]}`;
return netMask;
}
将ip转换成数字比较大小
function ipToNumber(ip) {
var numbers = ip.split('.');
return (
parseInt(numbers[0], 10) * 256 * 256 * 256 +
parseInt(numbers[1], 10) * 256 * 256 +
parseInt(numbers[2], 10) * 256 +
parseInt(numbers[3], 10)
);
}
|