如何解决算法:根据 CIDR 段和关键字获取 IPV6 地址的建议?
获取特定的 size
ipv6 地址计数,包括特定的 keyword
和内部特定的 cidr
function getIpAddresses(cidr: string,size: number,keyword: string): string[] {
// ...
}
input
和 output
演示:
getIpAddresses('fd00:100:64::/64',10,'1011')
// =>
[
'fd00:100:64:::::1011','fd00:100:64::::1:1011','fd00:100:64::::2:1011','fd00:100:64::::3:1011','fd00:100:64::::4:1011','fd00:100:64::::5:1011','fd00:100:64::::6:1011','fd00:100:64::::7:1011','fd00:100:64::::8:1011','fd00:100:64::::9:1011'
]
相关 npm 包 ip-address
以下实现非常慢(对于这样一个简单的例子,运行大约需要 13 秒):
import { Address6 } from "ip-address";
import { BigInteger } from "jsbn";
const shortIpV6Address = (ipV6Address: string) =>
ipV6Address
.split(":")
.map((item) => item.replace(/^0+/,""))
.join(":");
export const getIpAddresses = (
cidrStr: string,keyword = ""
): string[] => {
keyword = keyword.trim();
const parts = keyword.split(":");
const result: string[] = [];
if (
parts.length > 8 ||
parts.some((word) => !/^[\dA-Fa-f]{0,4}$/.test(word))
) {
return result;
}
try {
const cidr = new Address6(cidrStr);
const startAddress = cidr._startAddress();
const endAddress = cidr._endAddress();
let addressNum = startAddress.add(BigInteger.ONE);
while (addressNum.compareTo(endAddress) < 0 && result.length < size) {
const { address } = Address6.fromBigInteger(addressNum);
const shortedAddress = shortIpV6Address(address);
if (
address.includes(keyword) ||
shortedAddress.includes(shortIpV6Address(keyword))
) {
result.push(shortedAddress);
}
addressNum = addressNum.add(BigInteger.ONE);
}
} catch {}
return result;
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。