os#networkInterfaces TypeScript Examples

The following examples show how to use os#networkInterfaces. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: sniffer.ts    From diablo2 with MIT License 6 votes vote down vote up
export function findLocalIps(): { address: string; interface: string }[] {
  const output: { address: string; interface: string }[] = [];
  const iFaces = networkInterfaces();
  for (const [name, iFace] of Object.entries(iFaces)) {
    if (iFace == null) continue;
    for (const ifa of iFace) {
      if (ifa.family !== 'IPv4' || ifa.internal !== false) {
        // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
        continue;
      }
      output.push({ address: ifa.address, interface: name });
    }
  }
  return output;
}
Example #2
Source File: addrs.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Checks the OS's network interfaces and returns the addresses of the requested interface
 * @param iface interface to use, e.g. `eth0`
 * @param __fakeInterfaces [testing] overwrite Node.js library function with test input
 * @returns
 */
function getAddrsOfInterface(iface: string, __fakeInterfaces?: ReturnType<typeof networkInterfaces>) {
  let ifaceAddrs = __fakeInterfaces ? __fakeInterfaces[iface] : networkInterfaces()[iface]

  if (ifaceAddrs == undefined) {
    log(
      `Interface <${iface}> does not exist on this machine. Available are <${Object.keys(networkInterfaces()).join(
        ', '
      )}>`
    )
    return []
  }

  return ifaceAddrs ?? []
}
Example #3
Source File: addrs.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
function getAddresses(cond: (address: Uint8Array, family: NetworkInterfaceInfo['family']) => boolean): Network[] {
  let result = []

  for (const iface of Object.values(networkInterfaces())) {
    for (const addr of iface ?? []) {
      const networkPrefix = toNetworkPrefix(addr)
      if (cond(ipToU8aAddress(addr.address, addr.family), addr.family)) {
        result.push(networkPrefix)
      }
    }
  }

  return result
}
Example #4
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
private getIp() {
    const interfaces = networkInterfaces(); // 在开发环境中获取局域网中的本机iP地址
    for (const devName in interfaces) {
      const iface = interfaces[devName];
      for (const alias of iface) {
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal
        ) {
          return alias.address;
        }
      }
    }
  }
Example #5
Source File: ip.ts    From TidGi-Desktop with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Copy from https://github.com/sindresorhus/internal-ip, to fi xsilverwind/default-gateway 's bug
 * @returns
 */
function findIp(gateway: string): string | undefined {
  const gatewayIp = ip.parse(gateway);

  // Look for the matching interface in all local interfaces.
  for (const addresses of Object.values(networkInterfaces())) {
    if (addresses !== undefined) {
      for (const { cidr } of addresses) {
        if (cidr) {
          const net = ip.parseCIDR(cidr);

          // eslint-disable-next-line unicorn/prefer-regexp-test
          if (net[0] && net[0].kind() === gatewayIp.kind() && gatewayIp.match(net)) {
            return net[0].toString();
          }
        }
      }
    }
  }
}
Example #6
Source File: addrs.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks the OS's network interfaces and return all desired addresses, such as local IPv4 addresses,
 * public IPv6 addresses etc.
 * @param port port to use
 * @param options which addresses to use
 * @param __fakeInterfaces [testing] overwrite Node.js library function with test input
 * @returns
 */
export function getAddrs(
  port: number,
  options: AddrOptions,
  __fakeInterfaces?: ReturnType<typeof networkInterfaces>
): AddressType[] {
  validateOptions(options)

  let interfaces: (NetworkInterfaceInfo[] | undefined)[]

  if (options?.interface) {
    interfaces = [getAddrsOfInterface(options.interface, __fakeInterfaces)]
  } else {
    interfaces = Object.values(__fakeInterfaces ?? networkInterfaces())
  }

  const multiaddrs: AddressType[] = []

  for (const iface of interfaces) {
    if (iface == undefined) {
      continue
    }

    for (const address of iface) {
      const u8aAddr = ipToU8aAddress(address.address, address.family)

      if (isLinkLocaleAddress(u8aAddr, address.family)) {
        continue
      }

      if (isPrivateAddress(u8aAddr, address.family)) {
        if (address.family === 'IPv4' && options.includePrivateIPv4 != true) {
          continue
        }
      }

      if (isLocalhost(u8aAddr, address.family)) {
        if (address.family === 'IPv4' && options.includeLocalhostIPv4 != true) {
          continue
        }
        if (address.family === 'IPv6' && options.includeLocalhostIPv6 != true) {
          continue
        }
      }

      if (address.family === 'IPv4' && options.useIPv4 != true) {
        continue
      }

      if (address.family === 'IPv6' && options.useIPv6 != true) {
        continue
      }

      multiaddrs.push({ ...address, port })
    }
  }

  return multiaddrs
}
Example #7
Source File: listener.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
private getAddressForInterface(host: string, family: NetworkInterfaceInfo['family']): string {
    if (this.options.interface == undefined) {
      return host
    }

    const osInterfaces = networkInterfaces()

    if (osInterfaces == undefined) {
      throw Error(`Machine seems to have no network interfaces.`)
    }

    if (osInterfaces[this.options.interface] == undefined) {
      throw Error(`Machine does not have requested interface ${this.options.interface}`)
    }

    const usableInterfaces = osInterfaces[this.options.interface]?.filter(
      (iface: NetworkInterfaceInfo) => iface.family == family && !iface.internal
    )

    if (usableInterfaces == undefined || usableInterfaces.length == 0) {
      throw Error(
        `Desired interface <${this.options.interface}> does not exist or does not have any external addresses.`
      )
    }

    const index = usableInterfaces.findIndex((iface) => host === iface.address)

    if (!isAnyAddress(host, family) && index < 0) {
      throw Error(
        `Could not bind to interface ${
          this.options.interface
        } on address ${host} because it was configured with a different addresses: ${usableInterfaces
          .map((iface) => iface.address)
          .join(`, `)}`
      )
    }

    // @TODO figure what to do if there is more than one address
    return usableInterfaces[0].address
  }