Full Code of DylanPiercey/local-devices for AI

master 8763bbdf4f96 cached
16 files
33.6 KB
10.6k tokens
19 symbols
1 requests
Download .txt
Repository: DylanPiercey/local-devices
Branch: master
Commit: 8763bbdf4f96
Files: 16
Total size: 33.6 KB

Directory structure:
gitextract_0on0dh1s/

├── .all-contributorsrc
├── .coveralls.yml.example
├── .gitignore
├── .nvmrc
├── .travis.yml
├── CHANGES.md
├── LICENCE
├── README.md
├── __tests__/
│   └── index.js
├── jest-setup.js
├── package.json
└── src/
    ├── index.d.ts
    ├── index.js
    └── parser/
        ├── index.js
        ├── linux.js
        └── win32.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .all-contributorsrc
================================================
{
  "projectName": "local-devices",
  "projectOwner": "DylanPiercey",
  "repoType": "github",
  "repoHost": "https://github.com",
  "files": [
    "README.md"
  ],
  "imageSize": 100,
  "commit": false,
  "commitConvention": "eslint",
  "contributors": [
    {
      "login": "DylanPiercey",
      "name": "Dylan Piercey",
      "avatar_url": "https://avatars2.githubusercontent.com/u/4985201?v=4",
      "profile": "https://twitter.com/dylan_piercey",
      "contributions": [
        "code",
        "example",
        "review",
        "doc",
        "ideas",
        "question"
      ]
    },
    {
      "login": "natterstefan",
      "name": "Stefan Natter",
      "avatar_url": "https://avatars2.githubusercontent.com/u/1043668?v=4",
      "profile": "http://twitter.com/natterstefan",
      "contributions": [
        "code",
        "test",
        "bug",
        "doc",
        "ideas"
      ]
    },
    {
      "login": "kounelios13",
      "name": "kounelios13",
      "avatar_url": "https://avatars3.githubusercontent.com/u/11466138?v=4",
      "profile": "https://github.com/kounelios13",
      "contributions": [
        "bug",
        "doc"
      ]
    },
    {
      "login": "MarkusSuomi",
      "name": "MarkusSuomi",
      "avatar_url": "https://avatars3.githubusercontent.com/u/5594334?v=4",
      "profile": "https://github.com/MarkusSuomi",
      "contributions": [
        "code"
      ]
    },
    {
      "login": "nolazybits",
      "name": "Xavier Martin",
      "avatar_url": "https://avatars1.githubusercontent.com/u/214998?v=4",
      "profile": "http://nolazybits.com",
      "contributions": [
        "code"
      ]
    },
    {
      "login": "howel52",
      "name": "howel52",
      "avatar_url": "https://avatars0.githubusercontent.com/u/9854818?v=4",
      "profile": "https://me.howel52.com/",
      "contributions": [
        "code",
        "bug"
      ]
    },
    {
      "login": "LucaSoldi",
      "name": "LucaSoldi",
      "avatar_url": "https://avatars0.githubusercontent.com/u/5584781?v=4",
      "profile": "https://github.com/LucaSoldi",
      "contributions": [
        "code",
        "bug"
      ]
    },
    {
      "login": "Miosame",
      "name": "Miosame",
      "avatar_url": "https://avatars1.githubusercontent.com/u/8201077?v=4",
      "profile": "https://github.com/Miosame",
      "contributions": [
        "code",
        "doc",
        "example"
      ]
    },
    {
      "login": "timrogers",
      "name": "Tim Rogers",
      "avatar_url": "https://avatars.githubusercontent.com/u/116134?v=4",
      "profile": "https://timrogers.co.uk",
      "contributions": [
        "code",
        "doc",
        "test"
      ]
    }
  ],
  "contributorsPerLine": 7
}


================================================
FILE: .coveralls.yml.example
================================================
# Inspired by https://github.com/Flexberry/javascript-project-template/blob/master/.coveralls.yml.example
# When built on Travis, Coveralls can detect the associated repo automatically.
# If you're running locally, you must have a .coveralls.yml file with your
# repo_token in it; or, you must provide a COVERALLS_REPO_TOKEN
# environment-variable on the command-line.

# The secret repo token for your repository, found at the bottom of your
# repository's page on Coveralls. DON'T ADD THIS TO PUBLIC REPO. Should be kept
# SECRET - anyone could use it to submit coverage data on your repo's behalf.
repo_token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

================================================
FILE: .gitignore
================================================
# VS Code
.vscode

# Sublime
*.sublime*

# OSX
*.DS_Store

# NPM
node_modules
npm-debug.log

# Testing
test/run.js
coverage
.coveralls.yml


================================================
FILE: .nvmrc
================================================
v10.17

================================================
FILE: .travis.yml
================================================
language: node_js

node_js:
  - '8'
  - '10'

script:
  - npm run test

notifications:
  email:
    on_success: change
    on_failure: always

after_success: 'npm run coveralls'

cache:
  directories:
    - ~/.npm # cache npm's cache
    - ~/npm # cache latest npm
    - node_modules # npm install, unlike npm ci, doesn't wipe node_modules

================================================
FILE: CHANGES.md
================================================
# Local-Devices

All notable changes to this project will be documented here. The format is based
on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project
adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [4.0.0] - 2022-08-15

### Changed

### Added

- support passing in an `arpPath` option to override the arp binary used ([#59](https://github.com/DylanPiercey/local-devices/pull/59))

⚠ BREAKING CHANGES

- switch to using an option object for the `find` api ([#59](https://github.com/DylanPiercey/local-devices/pull/59))

## [3.2.0] - 2021-09-21

### Added

- flag to skip name resolution ([#24](https://github.com/DylanPiercey/local-devices/pull/36))

## [3.1.0] - 2020-09-25

### Added

- support passing ip ranges to the `find` api ([#24](https://github.com/DylanPiercey/local-devices/pull/24))

## [3.0.0] - 2019-10-29

### Changed

⚠ BREAKING CHANGES

- dropping Node v8 support because [end-of-life](https://github.com/nodejs/Release#release-schedule)
  [[#18](https://github.com/DylanPiercey/local-devices/pull/18)]

### Fixes

- increase `maxBuffer` of `cp.exec` to 10MB (1024*1024*10), fixes [#10](https://github.com/DylanPiercey/local-devices/issues/10)
- fix: add timeout options when exec arp ([#13](https://github.com/DylanPiercey/local-devices/pull/13))
- Fixed win32 parser for better windows support ([#9](https://github.com/DylanPiercey/local-devices/pull/9))
- validate ip address before executing command for 'find' ([#16](https://github.com/DylanPiercey/local-devices/pull/16))

## [2.0.0] - 2019-02-10

### Added

- Support for Raspberry Pi (Linux)
- Partial support for windows
- Jest test suite and tests for Linux and other platforms
- with Travis CI integration
  
### Changed

- fixed npm module versions in package.json
- fixed node version to v8.14.1


================================================
FILE: LICENCE
================================================
The MIT License (MIT)

Copyright (c) 2018, Dylan Piercey and Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

================================================
FILE: README.md
================================================
# Local Devices

[![version][version-badge]][package]
[![MIT License][license-badge]][licence]
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
[![All Contributors](https://img.shields.io/badge/all_contributors-7-orange.svg?style=flat-square)](#contributors)
[![PRs Welcome][prs-badge]][prs]

[![Build Status][build-badge]][build]
[![Coverage Status][coverage-badge]][coverage]
[![Watch on GitHub][github-watch-badge]][github-watch]
[![Star on GitHub][github-star-badge]][github-star]

Find all devices connected to the local network using `arp -a`.
This module also pings all possible ip's in the local network to build the arp table.

## Installation

### Npm

```console
npm install local-devices
```

### Example

```javascript
// Using a transpiler
import find from 'local-devices'
// Without using a transpiler
const find = require('local-devices');

// Find all local network devices.
find().then(devices => {
  devices /*
  [
    { name: '?', ip: '192.168.0.10', mac: '...' },
    { name: '...', ip: '192.168.0.17', mac: '...' },
    { name: '...', ip: '192.168.0.21', mac: '...' },
    { name: '...', ip: '192.168.0.22', mac: '...' }
  ]
  */
})

// Find a single device by ip address.
find({ address: '192.168.0.10' }).then(device => {
  device /*
  {
    name: '?',
    ip: '192.168.0.10',
    mac: '...'
  }
  */
})

// Find all devices within 192.168.0.1 to 192.168.0.25 range
find({ address: '192.168.0.1-192.168.0.25' }).then(devices => {
    devices /*
    [
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.17', mac: '...' },
      { name: '...', ip: '192.168.0.21', mac: '...' },
      { name: '...', ip: '192.168.0.22', mac: '...' }
    ]
    */
})

// Find all devices within /24 subnet range of 192.168.0.x
find({ address: '192.168.0.0/24' }).then(devices => {
    devices /*
    [
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '...', ip: '192.168.0.50', mac: '...' },
      { name: '...', ip: '192.168.0.155', mac: '...' },
      { name: '...', ip: '192.168.0.211', mac: '...' }
    ]
    */
})

// Find all devices without resolving host names (Uses 'arp -an') - this is more performant if hostnames are not needed 
// (This flag is ignored on Windows machines as 'arp -an' is not supported)
find({ skipNameResolution: true }).then(devices => {
    devices /*
    [
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '?', ip: '192.168.0.50', mac: '...' },
      { name: '?', ip: '192.168.0.155', mac: '...' },
      { name: '?', ip: '192.168.0.211', mac: '...' }
    ]
    */
})

// Find all devices, specifying your own path for the `arp` binary 
find({ arpPath: '/usr/sbin/arp' }).then(devices => {
    devices /*
    [
      { name: '?', ip: '192.168.0.10', mac: '...' },
      { name: '?', ip: '192.168.0.50', mac: '...' },
      { name: '?', ip: '192.168.0.155', mac: '...' },
      { name: '?', ip: '192.168.0.211', mac: '...' }
    ]
    */
})
```

## Contributions

* Use `npm test` to run tests.

Please feel free to create a PR!

## Contributors

Thanks goes to these wonderful people ([emoji key][emojis]):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
  <tr>
    <td align="center"><a href="https://twitter.com/dylan_piercey"><img src="https://avatars2.githubusercontent.com/u/4985201?v=4" width="100px;" alt="Dylan Piercey"/><br /><sub><b>Dylan Piercey</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=DylanPiercey" title="Code">💻</a> <a href="#example-DylanPiercey" title="Examples">💡</a> <a href="#review-DylanPiercey" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=DylanPiercey" title="Documentation">📖</a> <a href="#ideas-DylanPiercey" title="Ideas, Planning, & Feedback">🤔</a> <a href="#question-DylanPiercey" title="Answering Questions">💬</a></td>
    <td align="center"><a href="http://twitter.com/natterstefan"><img src="https://avatars2.githubusercontent.com/u/1043668?v=4" width="100px;" alt="Stefan Natter"/><br /><sub><b>Stefan Natter</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=natterstefan" title="Code">💻</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=natterstefan" title="Tests">⚠️</a> <a href="https://github.com/DylanPiercey/local-devices/issues?q=author%3Anatterstefan" title="Bug reports">🐛</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=natterstefan" title="Documentation">📖</a> <a href="#ideas-natterstefan" title="Ideas, Planning, & Feedback">🤔</a></td>
    <td align="center"><a href="https://github.com/kounelios13"><img src="https://avatars3.githubusercontent.com/u/11466138?v=4" width="100px;" alt="kounelios13"/><br /><sub><b>kounelios13</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/issues?q=author%3Akounelios13" title="Bug reports">🐛</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=kounelios13" title="Documentation">📖</a></td>
    <td align="center"><a href="https://github.com/MarkusSuomi"><img src="https://avatars3.githubusercontent.com/u/5594334?v=4" width="100px;" alt="MarkusSuomi"/><br /><sub><b>MarkusSuomi</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=MarkusSuomi" title="Code">💻</a></td>
    <td align="center"><a href="http://nolazybits.com"><img src="https://avatars1.githubusercontent.com/u/214998?v=4" width="100px;" alt="Xavier Martin"/><br /><sub><b>Xavier Martin</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=nolazybits" title="Code">💻</a></td>
    <td align="center"><a href="https://me.howel52.com/"><img src="https://avatars0.githubusercontent.com/u/9854818?v=4" width="100px;" alt="howel52"/><br /><sub><b>howel52</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=howel52" title="Code">💻</a> <a href="https://github.com/DylanPiercey/local-devices/issues?q=author%3Ahowel52" title="Bug reports">🐛</a></td>
    <td align="center"><a href="https://github.com/LucaSoldi"><img src="https://avatars0.githubusercontent.com/u/5584781?v=4" width="100px;" alt="LucaSoldi"/><br /><sub><b>LucaSoldi</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=LucaSoldi" title="Code">💻</a> <a href="https://github.com/DylanPiercey/local-devices/issues?q=author%3ALucaSoldi" title="Bug reports">🐛</a></td>
  </tr>
  <tr>
    <td align="center"><a href="https://github.com/Miosame"><img src="https://avatars1.githubusercontent.com/u/8201077?v=4" width="100px;" alt="Miosame"/><br /><sub><b>Miosame</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=Miosame" title="Code">💻</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=Miosame" title="Documentation">📖</a> <a href="#example-Miosame" title="Examples">💡</a></td>
    <td align="center"><a href="https://timrogers.co.uk"><img src="https://avatars.githubusercontent.com/u/116134?v=4" width="100px;" alt="Tim Rogers"/><br /><sub><b>Tim Rogers</b></sub></a><br /><a href="https://github.com/DylanPiercey/local-devices/commits?author=timrogers" title="Code">💻</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=timrogers" title="Documentation">📖</a> <a href="https://github.com/DylanPiercey/local-devices/commits?author=timrogers" title="Tests">⚠️</a></td>
  </tr>
</table>

<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->

This project follows the [all-contributors][all-contributors] specification.
Contributions of any kind are welcome!

### How to add Contributors

Contributors can be added with the [all-contributors cli](https://allcontributors.org/docs/en/cli/installation).
The cli is already installed and can be [used like this](https://allcontributors.org/docs/en/bot/usage):

```bash
yarn all-contributors add <username> <emoji-keys>
```

## LICENCE

[MIT](LICENCE)

[package]: https://www.npmjs.com/package/local-devices
[licence]: https://github.com/DylanPiercey/local-devices/blob/master/LICENCE
[prs]: http://makeapullrequest.com
[github-watch]: https://github.com/DylanPiercey/local-devices/watchers
[github-star]: https://github.com/DylanPiercey/local-devices/stargazers
[github-watch-badge]: https://img.shields.io/github/watchers/DylanPiercey/local-devices.svg?style=social
[github-star-badge]: https://img.shields.io/github/stars/DylanPiercey/local-devices.svg?style=social
[version-badge]: https://img.shields.io/npm/v/local-devices.svg?style=flat-square
[license-badge]: https://img.shields.io/npm/l/local-devices.svg?style=flat-square
[prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
[emojis]: https://github.com/kentcdodds/all-contributors#emoji-key
[all-contributors]: https://github.com/kentcdodds/all-contributors

[build-badge]: https://travis-ci.org/DylanPiercey/local-devices.svg?branch=master
[build]: https://travis-ci.org/DylanPiercey/local-devices
[coverage-badge]: https://coveralls.io/repos/github/DylanPiercey/local-devices/badge.svg?branch=master
[coverage]: https://coveralls.io/github/DylanPiercey/local-devices?branch=master


================================================
FILE: __tests__/index.js
================================================
const find = require('../src/index')
var cp = require('mz/child_process')

const TEN_MEGA_BYTE = 1024 * 1024 * 10
const ONE_MINUTE = 60 * 1000

describe('local-devices', () => {
  const platforms = [
    'linux',
    'darwin',
    'win32'
  ]

  beforeAll(() => {
    this.originalPlatform = process.platform
  })

  afterAll(() => {
    Object.defineProperty(process, 'platform', {
      value: this.originalPlatform
    })
  })

  platforms.forEach(platform => {
    describe(`on ${platform}`, () => {
      beforeAll(() => {
        Object.defineProperty(process, 'platform', {
          value: platform
        })
      })

      afterEach(() => cp.exec.mockClear())

      it('returns the result of all IPs', async () => {
        const result = await find()
        expect(result).toEqual([
          { name: '?', ip: '192.168.0.202', mac: '00:12:34:56:78:90' },
          { name: '?', ip: '192.168.0.212', mac: '00:12:34:56:78:91' },
          { name: '?', ip: '192.168.0.222', mac: '00:12:34:56:78:92' },
          { name: '?', ip: '192.168.0.232', mac: '00:12:34:56:78:93' },
          { name: '?', ip: '192.168.1.234', mac: '00:12:34:56:78:94' }
        ])
      })

      it('returns empty list if empty response returned', async () => {
        cp.exec.mockImplementationOnce(_ => Promise.resolve())
        const result = await find()
        expect(result).toEqual([])
      })

      it('returns all IPs within /24 range', async () => {
        const result = await find({ address: '192.168.1.0/24' })
        expect(result).toEqual([
          { name: '?', ip: '192.168.1.234', mac: '00:12:34:56:78:94' }
        ])
      })

      it('returns all IPs within 1-254 range', async () => {
        const result = await find({ address: '192.168.1.1-192.168.1.254' })
        expect(result).toEqual([
          { name: '?', ip: '192.168.1.234', mac: '00:12:34:56:78:94' }
        ])
      })

      it('returns the result of a single IP (Note: undefined on win32)', async () => {
        const result = await find({ address: '192.168.0.222' })

        if (process.platform.includes('win32')) {
          // not supported yet
          expect(result).toBeUndefined()
          return
        }

        expect(result).toEqual(
          { name: '?', ip: '192.168.0.222', mac: '00:12:34:56:78:92' }
        )
      })

      it('returns undefined, when the host is not resolved', async () => {
        const result = await find({ address: '192.168.0.242' })
        expect(result).toBeUndefined()
      })

      it('returns undefined, when the host does not exist in arp table', async () => {
        const result = await find({ address: '192.168.0.243' })
        expect(result).toBeUndefined()
      })

      it('rejects when the host is not a valid ip address', async () => {
        await expect(find({ address: '127.0.0.1 | mkdir attacker' })).rejects.toThrow('Invalid IP')
      })

      it('invokes cp.exec with maxBuffer of 10 MB and a timeout of 1 minute, when invoking find without an ip', async () => {
        await find()
        expect(cp.exec).toHaveBeenCalledWith('arp -a', { maxBuffer: TEN_MEGA_BYTE, timeout: ONE_MINUTE })
      })

      it('invokes cp.exec with maxBuffer of 10 MB and a timeout of 1 minute, when invoking find without an ip and skip name resolution', async () => {
        await find({ address: null, skipNameResolution: true })
        if (process.platform.includes('win32')) {
          expect(cp.exec).toHaveBeenCalledWith('arp -a', { maxBuffer: TEN_MEGA_BYTE, timeout: ONE_MINUTE })
        } else {
          expect(cp.exec).toHaveBeenCalledWith('arp -an', { maxBuffer: TEN_MEGA_BYTE, timeout: ONE_MINUTE })
        }
      })

      it('invokes cp.exec with maxBuffer of 10 MB and a timeout of 1 minute, when invoking find with a single ip', async () => {
        await find({ address: '192.168.0.242' })
        expect(cp.exec).toHaveBeenCalledWith('arp -n 192.168.0.242', { maxBuffer: TEN_MEGA_BYTE, timeout: ONE_MINUTE })
      })

      it('invokes cp.exec with maxBuffer of 10 MB, a timeout of 1 minute and a custom arp binary, when invoking find with an arpPath', async () => {
        await (find({ arpPath: '/usr/sbin/arp' }))
        expect(cp.exec).toHaveBeenCalledWith('/usr/sbin/arp -a', { maxBuffer: TEN_MEGA_BYTE, timeout: ONE_MINUTE })
      })
    })
  })
})


================================================
FILE: jest-setup.js
================================================
/**
 * MOCKS
 */
const mockHosts = [
  '? (192.168.0.202) at 00:12:34:56:78:90 on en0 ifscope [ethernet]',
  '? (192.168.0.212) at 00:12:34:56:78:91 on en0 ifscope [ethernet]',
  '? (192.168.0.222) at 00:12:34:56:78:92 on en0 ifscope [ethernet]',
  '? (192.168.0.232) at 00:12:34:56:78:93 on en0 ifscope [ethernet]',
  '? (192.168.1.234) at 00:12:34:56:78:94 on en0 ifscope [ethernet]',
  // "special" cases (eg. unresolved hosts)
  '? (192.168.0.242) at (incomplete) on en0 ifscope [ethernet]', // host is in the list but incomplete
  '192.168.0.243 (192.168.0.243) -- no entry' // host has no entry in the arp table
]

const mockLinuxHosts = [
  '? (192.168.0.202) at 00:12:34:56:78:90 [ether] on eth0',
  '? (192.168.0.212) at 00:12:34:56:78:91 [ether] on eth0',
  '? (192.168.0.222) at 00:12:34:56:78:92 [ether] on eth0',
  '? (192.168.0.232) at 00:12:34:56:78:93 [ether] on eth0',
  '? (192.168.1.234) at 00:12:34:56:78:94 [ether] on eth0',
  // "special" cases (eg. unresolved hosts)
  '? (192.168.0.242) at <incomplete> on eth0',
  '192.168.0.243 (192.168.0.243) -- no entry' // host has no entry in the arp table
]

/* eslint-disable */
// NOTE: may not cover all test cases yet
const mockWinHosts = [
  '192.168.0.202	00-12-34-56-78-90	dynamic',
  '192.168.0.212	00-12-34-56-78-91	dynamic',
  '192.168.0.222	00-12-34-56-78-92	dynamic',
  '192.168.0.232	00-12-34-56-78-93	dynamic',
  '192.168.1.234	00-12-34-56-78-94	dynamic',
  // "special" cases (eg. unresolved hosts)
  '192.168.1.242	(incomplete)	dynamic',
]
/* eslint-enable */

function mockPrepareHosts (command) {
  // first filter all special case examples from the mockHost list (eg. no entry)
  const workingHosts = mockHosts.filter(i => i.indexOf('no entry') < 0)
  let r = workingHosts.join('\n')

  if (command.includes('-n')) {
    const ip = command.match(/arp -(.*){1} (.*)/)[2]
    r = mockHosts.find(i => i.indexOf(ip) > 0)
  }

  return r
}

function mockPrepareLinuxHosts (command) {
  // first filter all special case examples from the mockHost list (eg. no entry)
  const workingHosts = mockLinuxHosts.filter(i => i.indexOf('no entry') < 0)
  let r = workingHosts.join('\n')

  // then define the current use-case (arp all or arp one)
  if (command.includes('-n')) {
    // receive the ip address of the request and the mac address from the mocked hosts
    const ip = command.match(/arp -(.*){1} (.*)/)[2]
    const host = mockLinuxHosts.find(i => i.indexOf(ip) >= 0)

    // and finally prepare the arp output for the tests
    if (host.indexOf('no entry') >= 0) {
      r = host
    } else {
      const macAddress = host.split(' ')[3]
      r = `Address                  HWtype  HWaddress           Flags Mask            Iface
${ip}             ether   ${macAddress}   C                     eth0`
    }
  }

  return r
}

function mockPrepareWin (command) {
  // first filter all special case examples from the mockHost list (eg. no entry)
  const workingHosts = mockWinHosts.filter(i => i.indexOf('no entry') < 0)
  /* eslint-disable-next-line */
  workingHosts.unshift('Internet Address	Physical Address	Type')
  let r = workingHosts.join('\n')

  if (command.includes('-n')) {
    // only for TESTS, win32 will return the manual text instead
    r = 'scanning a specific IP is not supported on Windows with local-devices'
  }
  return r
}

jest.mock('mz/child_process', () => ({
  exec: jest.fn(command => {
    var r = mockPrepareHosts(command)
    if (process.platform === 'linux') {
      r = mockPrepareLinuxHosts(command)
    } else if (process.platform === 'win32') {
      r = mockPrepareWin(command)
    }
    return new Promise(resolve => resolve([r]))
  })
}))

// Mock net.Socket (Alternative (not tested yet): https://www.npmjs.com/package/mitm)
jest.mock('net', () => ({
  Socket: jest.fn(() => ({
    setTimeout: jest.fn((timeout, cb) => {
      cb()
    }),
    destroy: jest.fn(),
    connect: jest.fn((port, address, cb) => {
      cb()
    }),
    once: jest.fn((timeout, cb) => {
      cb()
    })
  }))
}))

jest.mock('os', () => ({
  // example mock for darwin (MacOSX)
  networkInterfaces: jest.fn().mockReturnValue({
    lo0:
      [{
        address: '127.0.0.1',
        netmask: '255.0.0.0',
        family: 'IPv4',
        mac: '00:00:00:00:00:00',
        internal: true,
        cidr: '127.0.0.1/8'
      }],
    utun0:
      [{
        address: 'as12::d3f4:56j:k789:0l00',
        netmask: 'ffff:ffff:ffff:ffff::',
        family: 'IPv6',
        mac: '00:00:00:00:00:00',
        scopeid: 11,
        internal: false,
        cidr: 'as12::d3f4:56j:k789:0l00/64'
      }],
    en5:
      [{
        address: '192.168.0.200',
        netmask: '255.255.254.0',
        family: 'IPv4',
        mac: '00:12:34:56:78:99',
        internal: false,
        cidr: '192.168.0.0/23'
      }]
  })
}))


================================================
FILE: package.json
================================================
{
  "name": "local-devices",
  "description": "Find devices connected to the current local network.",
  "version": "4.0.0",
  "author": "Dylan Piercey <pierceydylan@gmail.com>",
  "license": "MIT",
  "main": "src/index.js",
  "files": [
    "src"
  ],
  "scripts": {
    "contributors:add": "all-contributors add",
    "contributors:generate": "all-contributors generate",
    "coveralls": "jest --coverage && cat ./coverage/lcov.info | coveralls",
    "lint": "standard --verbose | snazzy",
    "test": "jest",
    "pretest": "npm run lint",
    "watch-test": "jest --watch"
  },
  "types": "./src/index.d.ts",
  "dependencies": {
    "get-ip-range": "^2.1.0",
    "ip": "^1.1.5",
    "mz": "^2.7.0"
  },
  "devDependencies": {
    "@types/jest": "^24.0.19",
    "all-contributors-cli": "^6.9.3",
    "coveralls": "^3.0.7",
    "husky": "^3.0.9",
    "jest": "^24.9.0",
    "lint-staged": "^9.4.2",
    "snazzy": "^8.0.0",
    "standard": "^14.3.1"
  },
  "engines": {
    "node": ">=10.17"
  },
  "homepage": "https://github.com/DylanPiercey/local-devices",
  "bugs": "https://github.com/DylanPiercey/local-devices/issues",
  "keywords": [
    "arp",
    "devices",
    "ip",
    "local",
    "mac",
    "mac-address",
    "scan"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/DylanPiercey/local-devices"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "pre-push": "npm test"
    }
  },
  "lint-staged": {
    "*.js": [
      "npm run lint",
      "git update-index --again",
      "jest --findRelatedTests"
    ]
  },
  "jest": {
    "setupFiles": [
      "./jest-setup.js"
    ]
  },
  "standard": {
    "globals": [
      "jest",
      "describe",
      "beforeAll",
      "afterAll",
      "beforeEach",
      "afterEach",
      "it",
      "expect"
    ]
  }
}


================================================
FILE: src/index.d.ts
================================================
declare module "local-devices" {

    function findLocalDevices(opts?: { address?: any, skipNameResolution?: boolean, arpPath?: string }): Promise<findLocalDevices.IDevice[]>;

    namespace findLocalDevices
    {
        interface IDevice
        {
            name: string;
            ip: string;
            mac: string;
        }
    }

    export = findLocalDevices;
}

================================================
FILE: src/index.js
================================================
var ip = require('ip')
var os = require('os')
var net = require('net')
var cp = require('mz/child_process')
var getIPRange = require('get-ip-range')

var parseLinux = require('./parser/linux')
var parseWin32 = require('./parser/win32')
var parseRow = require('./parser')

var servers
var lock = {}

const TEN_MEGA_BYTE = 1024 * 1024 * 10
const ONE_MINUTE = 60 * 1000
const options = {
  maxBuffer: TEN_MEGA_BYTE,
  timeout: ONE_MINUTE
}

/**
 * Finds all local devices (ip and mac address) connected to the current network.
 */
module.exports = function findLocalDevices ({ address = '', skipNameResolution = false, arpPath = 'arp' } = {}) {
  var key = String(address)

  if (isRange(address)) {
    try {
      servers = getIPRange(key)
    } catch (error) {
      // Note: currently doesn't throw the intended error message from the package maintainer
      // It will still be caught, PR here though: https://github.com/JoeScho/get-ip-range/pull/6
      return error
    }
  } else {
    servers = getServers()
  }

  if (!lock[key]) {
    if (!address || isRange(key)) {
      lock[key] = pingServers().then(() => arpAll(skipNameResolution, arpPath)).then(unlock(key))
    } else {
      lock[key] = pingServer(address).then(address => arpOne(address, arpPath)).then(unlock(key))
    }
  }

  return lock[key]
}

function isRange (address) {
  return address && new RegExp('/|-').test(address)
}

/**
 * Gets the current list of possible servers in the local networks.
 */
function getServers () {
  var interfaces = os.networkInterfaces()
  var result = []

  for (var key in interfaces) {
    var addresses = interfaces[key]
    for (var i = addresses.length; i--;) {
      var address = addresses[i]
      if (address.family === 'IPv4' && !address.internal) {
        var subnet = ip.subnet(address.address, address.netmask)
        var current = ip.toLong(subnet.firstAddress)
        var last = ip.toLong(subnet.lastAddress) - 1
        while (current++ < last) result.push(ip.fromLong(current))
      }
    }
  }

  return result
}

/**
 * Sends a ping to all servers to update the arp table.
 */
function pingServers () {
  return Promise.all(servers.map(pingServer))
}

/**
 * Pings an individual server to update the arp table.
 */
function pingServer (address) {
  return new Promise(function (resolve) {
    var socket = new net.Socket()
    socket.setTimeout(1000, close)
    socket.connect(80, address, close)
    socket.once('error', close)

    function close () {
      socket.destroy()
      resolve(address)
    }
  })
}

/**
 * Reads the arp table.
 */
function arpAll (skipNameResolution = false, arpPath) {
  const isWindows = process.platform.includes('win32')
  const cmd = (skipNameResolution && !isWindows) ? `${arpPath} -an` : `${arpPath} -a`
  return cp.exec(cmd, options).then(parseAll)
}

/**
 * Parses arp scan data into a useable collection.
 */
function parseAll (data) {
  if (!data || !data[0]) {
    return []
  }

  if (process.platform.includes('linux')) {
    var rows = data[0].split('\n')
    return rows.map(function (row) {
      return parseLinux(row, servers)
    }).filter(Boolean)
  } else if (process.platform.includes('win32')) {
    var winRows = data[0].split('\n').splice(1)
    return winRows.map(function (row) {
      return parseWin32(row, servers)
    }).filter(Boolean)
  }

  return data[0]
    .trim()
    .split('\n')
    .map(function (row) {
      return parseRow(row, servers)
    })
    .filter(Boolean)
}

/**
 * Reads the arp table for a single address.
 */
function arpOne (address, arpPath) {
  if (!ip.isV4Format(address) && !ip.isV6Format(address)) {
    return Promise.reject(new Error('Invalid IP address provided.'))
  }

  return cp.exec(`${arpPath} -n ${address}`, options).then(parseOne)
}

/**
 * Parses a single row of arp data.
 */
function parseOne (data) {
  if (!data || !data[0]) {
    return
  }

  if (process.platform.includes('linux')) {
    // ignore unresolved hosts (can happen when parseOne returns only one unresolved host)
    if (data[0].indexOf('no entry') >= 0) {
      return
    }

    // remove first row (containing "headlines")
    var rows = data[0].split('\n').slice(1)[0]
    return parseLinux(rows, servers, true)
  } else if (process.platform.includes('win32')) {
    return // currently not supported
  }

  return parseRow(data[0], servers)
}

/**
 * Clears the current promise and unlocks (will ping servers again).
 */
function unlock (key) {
  return function (data) {
    lock[key] = null
    return data
  }
}


================================================
FILE: src/parser/index.js
================================================
/**
 * Parses each row in the arp table into { name, ip, mac }.
 */
module.exports = function parseRow (row, servers) {
  // Parse name.
  var nameStart = 0
  var nameEnd = row.indexOf('(') - 1
  var name = row.slice(nameStart, nameEnd)

  // Parse ip.
  var ipStart = nameEnd + 2
  var ipEnd = row.indexOf(')', ipStart)
  var ipAddress = row.slice(ipStart, ipEnd)
  // Only resolve external ips.
  if (!~servers.indexOf(ipAddress)) {
    return
  }

  // Parse mac
  var macStart = row.indexOf(' at ', ipEnd) + 4
  var macEnd = row.indexOf(' on ', macStart)
  var macAddress = row.slice(macStart, macEnd)
  // Ignore unresolved hosts.
  if (macAddress === '(incomplete)') {
    return
  }
  // Format for always 2 digits
  macAddress = macAddress
    .replace(/^.:/, '0$&')
    .replace(/:.(?=:|$)/g, ':0X$&')
    .replace(/X:/g, '')

  return {
    name: name,
    ip: ipAddress,
    mac: macAddress
  }
}


================================================
FILE: src/parser/linux.js
================================================
/**
 * Parses each row in the arp table into { name, ip, mac } on linux.
 *
 * partially inspired by https://github.com/goliatone/arpscan/blob/master/lib/arpscanner.js
 */
module.exports = function parseLinux (row, servers, parseOne) {
  var result = {}

  // Ignore unresolved hosts.
  if (row === '' || row.indexOf('incomplete') >= 0) {
    return
  }

  var chunks = row.split(' ').filter(Boolean)
  if (parseOne) {
    result = prepareOne(chunks)
  } else {
    result = prepareAll(chunks)
  }

  // Only resolve external ips.
  if (!~servers.indexOf(result.ip)) {
    return
  }

  return result
}

function prepareOne (chunks) {
  return {
    name: '?', // a hostname is not provided on the raspberry pi (linux)
    ip: chunks[0],
    mac: chunks[2]
  }
}

function prepareAll (chunks) {
  return {
    name: chunks[0],
    ip: chunks[1].match(/\((.*)\)/)[1],
    mac: chunks[3]
  }
}


================================================
FILE: src/parser/win32.js
================================================
/**
 * Parses each row in the arp table into { name, ip, mac } on win32.
 */
module.exports = function parseRow (row, servers) {
  var chunks = row.split(/\s+/g).filter(function (el) { return el.length > 1 })

  // Parse name.
  var ipAddress = chunks[0]
  // Only resolve external ips.
  if (!~servers.indexOf(ipAddress)) {
    return
  }

  // Parse mac
  var macAddress = chunks[1].replace(/-/g, ':')
  // Ignore unresolved hosts.
  if (macAddress === '(incomplete)') {
    return
  }

  return {
    name: '?', // unresolved
    ip: ipAddress,
    mac: macAddress
  }
}
Download .txt
gitextract_0on0dh1s/

├── .all-contributorsrc
├── .coveralls.yml.example
├── .gitignore
├── .nvmrc
├── .travis.yml
├── CHANGES.md
├── LICENCE
├── README.md
├── __tests__/
│   └── index.js
├── jest-setup.js
├── package.json
└── src/
    ├── index.d.ts
    ├── index.js
    └── parser/
        ├── index.js
        ├── linux.js
        └── win32.js
Download .txt
SYMBOL INDEX (19 symbols across 5 files)

FILE: __tests__/index.js
  constant TEN_MEGA_BYTE (line 4) | const TEN_MEGA_BYTE = 1024 * 1024 * 10
  constant ONE_MINUTE (line 5) | const ONE_MINUTE = 60 * 1000

FILE: jest-setup.js
  function mockPrepareHosts (line 39) | function mockPrepareHosts (command) {
  function mockPrepareLinuxHosts (line 52) | function mockPrepareLinuxHosts (command) {
  function mockPrepareWin (line 76) | function mockPrepareWin (command) {

FILE: src/index.d.ts
  type IDevice (line 7) | interface IDevice

FILE: src/index.js
  constant TEN_MEGA_BYTE (line 14) | const TEN_MEGA_BYTE = 1024 * 1024 * 10
  constant ONE_MINUTE (line 15) | const ONE_MINUTE = 60 * 1000
  function isRange (line 50) | function isRange (address) {
  function getServers (line 57) | function getServers () {
  function pingServers (line 80) | function pingServers () {
  function pingServer (line 87) | function pingServer (address) {
  function arpAll (line 104) | function arpAll (skipNameResolution = false, arpPath) {
  function parseAll (line 113) | function parseAll (data) {
  function arpOne (line 142) | function arpOne (address, arpPath) {
  function parseOne (line 153) | function parseOne (data) {
  function unlock (line 177) | function unlock (key) {

FILE: src/parser/linux.js
  function prepareOne (line 29) | function prepareOne (chunks) {
  function prepareAll (line 37) | function prepareAll (chunks) {
Condensed preview — 16 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (37K chars).
[
  {
    "path": ".all-contributorsrc",
    "chars": 2729,
    "preview": "{\n  \"projectName\": \"local-devices\",\n  \"projectOwner\": \"DylanPiercey\",\n  \"repoType\": \"github\",\n  \"repoHost\": \"https://git"
  },
  {
    "path": ".coveralls.yml.example",
    "chars": 646,
    "preview": "# Inspired by https://github.com/Flexberry/javascript-project-template/blob/master/.coveralls.yml.example\n# When built o"
  },
  {
    "path": ".gitignore",
    "chars": 139,
    "preview": "# VS Code\n.vscode\n\n# Sublime\n*.sublime*\n\n# OSX\n*.DS_Store\n\n# NPM\nnode_modules\nnpm-debug.log\n\n# Testing\ntest/run.js\ncover"
  },
  {
    "path": ".nvmrc",
    "chars": 6,
    "preview": "v10.17"
  },
  {
    "path": ".travis.yml",
    "chars": 339,
    "preview": "language: node_js\n\nnode_js:\n  - '8'\n  - '10'\n\nscript:\n  - npm run test\n\nnotifications:\n  email:\n    on_success: change\n "
  },
  {
    "path": "CHANGES.md",
    "chars": 1826,
    "preview": "# Local-Devices\n\nAll notable changes to this project will be documented here. The format is based\non [Keep a Changelog]("
  },
  {
    "path": "LICENCE",
    "chars": 1097,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2018, Dylan Piercey and Contributors\n\nPermission is hereby granted, free of charge,"
  },
  {
    "path": "README.md",
    "chars": 9408,
    "preview": "# Local Devices\n\n[![version][version-badge]][package]\n[![MIT License][license-badge]][licence]\n[![js-standard-style](htt"
  },
  {
    "path": "__tests__/index.js",
    "chars": 4331,
    "preview": "const find = require('../src/index')\nvar cp = require('mz/child_process')\n\nconst TEN_MEGA_BYTE = 1024 * 1024 * 10\nconst "
  },
  {
    "path": "jest-setup.js",
    "chars": 4809,
    "preview": "/**\n * MOCKS\n */\nconst mockHosts = [\n  '? (192.168.0.202) at 00:12:34:56:78:90 on en0 ifscope [ethernet]',\n  '? (192.168"
  },
  {
    "path": "package.json",
    "chars": 1820,
    "preview": "{\n  \"name\": \"local-devices\",\n  \"description\": \"Find devices connected to the current local network.\",\n  \"version\": \"4.0."
  },
  {
    "path": "src/index.d.ts",
    "chars": 374,
    "preview": "declare module \"local-devices\" {\n\n    function findLocalDevices(opts?: { address?: any, skipNameResolution?: boolean, ar"
  },
  {
    "path": "src/index.js",
    "chars": 4528,
    "preview": "var ip = require('ip')\nvar os = require('os')\nvar net = require('net')\nvar cp = require('mz/child_process')\nvar getIPRan"
  },
  {
    "path": "src/parser/index.js",
    "chars": 908,
    "preview": "/**\n * Parses each row in the arp table into { name, ip, mac }.\n */\nmodule.exports = function parseRow (row, servers) {\n"
  },
  {
    "path": "src/parser/linux.js",
    "chars": 892,
    "preview": "/**\n * Parses each row in the arp table into { name, ip, mac } on linux.\n *\n * partially inspired by https://github.com/"
  },
  {
    "path": "src/parser/win32.js",
    "chars": 574,
    "preview": "/**\n * Parses each row in the arp table into { name, ip, mac } on win32.\n */\nmodule.exports = function parseRow (row, se"
  }
]

About this extraction

This page contains the full source code of the DylanPiercey/local-devices GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 16 files (33.6 KB), approximately 10.6k tokens, and a symbol index with 19 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!