Created
May 5, 2022 04:57
-
-
Save shanewholloway/e7e0242c26e0cdc62f69238d6872cefe to your computer and use it in GitHub Desktop.
NodeJS snippet for iterating the `networkInterfaces()` in the same subnet as `ip_query`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {networkInterfaces} from 'os' | |
import {isIP, BlockList} from 'net' | |
export function * iter_subnet_matches(ip_query) { | |
let family = isIP(ip_query) | |
let ipv = 'ipv'+family | |
for (let [if_name, if_addrs] of Object.entries(networkInterfaces())) { | |
for (let each of if_addrs) { | |
if (family != each.family) | |
continue; | |
let [net, width] = each.cidr.split('/',2) | |
let bl = new BlockList() | |
bl.addSubnet(net, +width, ipv) | |
if (bl.check(ip_query, ipv)) | |
yield each | |
} | |
} | |
} | |
if ('demo') { | |
let addr = '172.17.7.23' | |
for (let match of iter_subnet_matches(addr)) | |
console.log({addr, match}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment