有一个IP地址列表,原始= "1.2.3.4“、"1.2.4.1”、"1.3.45.67“、"1.3.67.89”。这个列表有1000 s的IP地址。我想要创建与前两个八位数匹配的组。Group1 = "1.2.3.4“、"1.2.4.1”Group2 = "1.3.45.67“、"1.3.67.89”如何在nodejs中实现?
下面的代码可以工作,但是想知道更简单的方法来实现同样的.
let initArray=['172.25.17.42','172.21.17.5','172.22.45.2','172.22.66.5','172.25.5.2','172.21.8.27','172.25.13.30','172.21.14.13','172.21.17.5','172.05.17.42','172.06.17.5','172.07.45.2','172.06.66.5','172.05.5.2','172.07.8.27','172.05.13.30','172.06.14.13','172.07.17.5','172.11.17.42','172.12.17.5','172.11.45.2','172.12.66.5','172.33.5.2','172.40.8.27','172.33.13.30','172.40.14.13','172.50.17.5'];
initArray.sort();
var resArray = [];
initArray.forEach(function (eachIP) {
let ocTets = eachIP.split('.');
let twoOctets = ocTets[0]+'.'+ocTets[1];
resArray.push(twoOctets);
})
const counts = {};
for (var i = 0; i < resArray.length; i++) {
var num = resArray[i];//num = 171.21
counts[num] = counts[num] ? counts[num] + 1 : 1;//counts[171.21 = 1]
}
let sum = 0;
var newMap = new Map(Object.entries(counts));
var resMap = new Map();
console.log(newMap);
let keyarray = [];
let j=0;
newMap.forEach((value, key, thisMap) => {
sum+=value;
if(sum<=5){
keyarray.push(key);
}
else
{
keyarray.push(key);
console.log('keyarray:'+keyarray);
let keyStr = keyarray.toString();
resMap.set(keyStr, sum);
while (keyarray.length) { keyarray.pop(); }
sum = 0;
}
})
console.log(resMap)发布于 2019-12-18 19:35:54
ipv4 IP地址仅为32位数字.虽然人们可以方便地将IP看作一个四重组字符串,但是使用数字编写IP逻辑通常更容易。例如,在代码中对is进行排序,但是is是按字母数字排序的,这可能不是您想要的。因此,一种方法是将所有IP地址映射到数字,然后应用分组逻辑。
以IP地址172.25.17.42和172.25.5.2为例。这些分别映射到0xAC19112A和0xAC190502的十六进制。您可以立即看到前两个八位数匹配(0xAC19)。
给定IP的数字表示,只需将每个数字右移16位就可以得到所需的分组。或者,您可以屏蔽所需的两个八进制以外的位(请记住,JavaScript数字是64位)。
我会遵循这个食谱:
octets.
这是一些密码。
const ips = ['172.25.17.42', '172.21.17.5', '172.22.45.2', '172.22.66.5',
'172.25.5.2', '172.21.8.27', '172.25.13.30', '172.21.14.13', '172.21.17.5',
'172.05.17.42', '172.06.17.5', '172.07.45.2', '172.06.66.5', '172.05.5.2',
'172.07.8.27', '172.05.13.30', '172.06.14.13', '172.07.17.5', '172.11.17.42',
'172.12.17.5', '172.11.45.2', '172.12.66.5', '172.33.5.2', '172.40.8.27',
'172.33.13.30', '172.40.14.13', '172.50.17.5'];
// Reduce the array of IPs down to a map of first-two-octets to IP.
const octetMap = ips
.reduce((map, ip) => {
// The first two octets of the IP as a number.
const firstTwo = ip2int(ip) >> 16;
// Alternative approach (JS numbers are 64 bit).
//const firstTwo = ip2int(ip) & 0x00FF0000;
// First time seeing firstTwo initialize an array, then add the IP.
if (!map.has(firstTwo))
map.set(firstTwo, []);
map.get(firstTwo).push(ip);
return map;
}, new Map());
console.log(octetMap);
// This returns an unsigned 32-bit integer representation of the ip string.
function ip2int(ip) {
return ip
.split('.')
.reduce((num, oct) => (num << 8) + parseInt(oct, 10), 0) >>> 0;
}https://stackoverflow.com/questions/59376122
复制相似问题