Giter Site home page Giter Site logo

node-ip's Introduction

IP

IP address utilities for node.js

Installation

npm

npm install ip

git

git clone https://github.com/indutny/node-ip.git

Usage

Get your ip address, compare ip addresses, validate ip addresses, etc.

var ip = require('ip');

ip.address() // my ip address
ip.isEqual('::1', '::0:1'); // true
ip.toBuffer('127.0.0.1') // Buffer([127, 0, 0, 1])
ip.toString(new Buffer([127, 0, 0, 1])) // 127.0.0.1
ip.fromPrefixLen(24) // 255.255.255.0
ip.mask('192.168.1.134', '255.255.255.0') // 192.168.1.0
ip.cidr('192.168.1.134/26') // 192.168.1.128
ip.not('255.255.255.0') // 0.0.0.255
ip.or('192.168.1.134', '0.0.0.255') // 192.168.1.255
ip.isPrivate('127.0.0.1') // true
ip.isV4Format('127.0.0.1'); // true
ip.isV6Format('::ffff:127.0.0.1'); // true

// operate on buffers in-place
var buf = new Buffer(128);
var offset = 64;
ip.toBuffer('127.0.0.1', buf, offset);  // [127, 0, 0, 1] at offset 64
ip.toString(buf, offset, 4);            // '127.0.0.1'

// subnet information
ip.subnet('192.168.1.134', '255.255.255.192')
// { networkAddress: '192.168.1.128',
//   firstAddress: '192.168.1.129',
//   lastAddress: '192.168.1.190',
//   broadcastAddress: '192.168.1.191',
//   subnetMask: '255.255.255.192',
//   subnetMaskLength: 26,
//   numHosts: 62,
//   length: 64,
//   contains: function(addr){...} }
ip.cidrSubnet('192.168.1.134/26')
// Same as previous.

// range checking
ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.190') // true


// ipv4 long conversion
ip.toLong('127.0.0.1'); // 2130706433
ip.fromLong(2130706433); // '127.0.0.1'

License

This software is licensed under the MIT License.

Copyright Fedor Indutny, 2012.

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.

node-ip's People

Contributors

bcbailey-godaddy avatar bryanwayb avatar codeanimal avatar donspaulding avatar drudge avatar heapwolf avatar huerlisi avatar indexzero avatar indutny avatar kostiak avatar mehaase avatar mmalecki avatar nw avatar wanderview avatar wavded avatar ym avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-ip's Issues

Improve perfomance

Hello, i'm author of ip2buf - a most faster js library for convering ip to the buffer. Implementation taken from libuv and ported from c++ (by hands, without emscripten). It is possible to join our work?

Some perf results:

For IPv4:

native: 264.411ms
ip2buf: 262.467ms
ipaddr.js: 1512.310ms
ip: 1047.124ms

For IPv6:

native: 316.183ms
ip2buf: 657.819ms
ipaddr.js: 1691.943ms
ip: 1358.625ms

Feature Request: subnetContains(subnet, ip) -> bool

Given a subnet and an IP address, I'd like to know if the address falls within the usable addresses of the subnet. A rough draft of the API I'm interested in would look something like this:

ip.subnetContains('192.168.1.1/24', '192.168.1.14');
// true
ip.subnetContains('192.168.0.1/24', '192.168.1.14');
// false

partial ips for CIDR seem not valid

Shouldn't address 127.0.10/24 be a valid CIDR?

cidrSubnet('127.0.10/24')

gives
Error: Invalid ip address: 127.0.10
I haven't found it on the specification but didn't do a deep read. They are certainly valid and other languages accept it

Bash on Windows networkinterface error

Crashes on Bash on Windows with the following error:

/home/ohad/projects/Coindash/node_modules/ip/lib/ip.js:353
  var interfaces = os.networkInterfaces();
                      ^

Error: EINVAL: invalid argument, uv_interface_addresses
    at Error (native)
    at Object.ip.address (/home/ohad/projects/Coindash/node_modules/ip/lib/ip.js:353:23)
    at Object.appStarted (/home/ohad/projects/Coindash/server/logger.js:30:41)
    at Server.app.listen (/home/ohad/projects/Coindash/server/index.js:41:12)
    at Server.g (events.js:291:16)
    at emitNone (events.js:86:13)
    at Server.emit (events.js:185:7)
    at emitListeningNT (net.js:1278:10)
    at _combinedTickCallback (internal/process/next_tick.js:71:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
    at Module.runMain (module.js:592:11)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

npm ERR! Linux 3.4.0+
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "start"
npm ERR! node v6.6.0
npm ERR! npm  v3.10.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] start: `cross-env NODE_ENV=development node server`
npm ERR! Exit status 1

Should be a very simple fix, as seen here: http-party/node-portfinder#42

cidrSubnet() is skipping first/last address

AFAIK, ip.cidrSubnet('192.168.1.0/30') should return 4 hosts in the range 192.168.1.0 - 192.168.1.3, but it actually returns 2 hosts in the range 192.168.1.1 - 192.168.1.2.

I checked out the source code and the reason is pretty obvious in subnet():

firstAddress: numberOfAddresses <= 2 ?
                    ip.fromLong(networkAddress) :
                    ip.fromLong(networkAddress + 1),

However, I can't understand the reason of such implementation. What am I missing?

Thank you,
Marco

Support CIDR subnet notation

Similar to the existing support for

 ip.mask('192.168.1.134', '255.255.255.0') // 192.168.1.0

How about?

ip.cidr('192.168.1.134', 24) // 192.168.1.0

I think it would also be nice to return an object that represents a subnet:

ip.cidr('192.168.1.134', 24) 
// {
//    subnetMask:24,
//    networkAddress:'192.168.1.10',
//    broadcastAddress:'192.168.1.255',
//    firstAddress:'192.168.1.1',
//    lastAddress:'192.168.1.254',
//    length:254
// }

What do you think?

Wrong IPv6 returned

NodeJS version: 6.0.0

JS Source:

ip.address( 'public', 'ipv6' ) // returns fe80::ad42:39c7:ff81:733

OS:

$ ip addr
ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
  inet6 2003:6a:6808:3f01:64d6:e507:513e:71ec/64 scope global mngtmpaddr noprefixroute dynamic

I shortened the output just because the rest is not important :)

Thank you in advance!


Updated NodeJS to max ( actually 6.1.0 ) still the same error.

I attach also the native output of NodeJS:

console.log( require('os').networkInterfaces() );
/*
ens160:
   [ ...
     { address: '2003:6a:6808:3f01:64d6:e507:513e:71ec',
       netmask: 'ffff:ffff:ffff:ffff::',
       family: 'IPv6',
       mac: 'xxx',
       scopeid: 0,
       internal: false },
     { address: 'fe80::ad42:39c7:ff81:733',
       netmask: 'ffff:ffff:ffff:ffff::',
       family: 'IPv6',
       mac: 'xxx',
       scopeid: 2,
       internal: false } ] }
*/

isV4Format

isV4Format('1.1.1.256') returned "true".
isV4Format('1.1.1.257') returned "true".

It seems intentional that did not handle exceptions.. right?

Possible enhancement?

Would be cool if together with ip.address(), we could have ip.gateway(cb), that returns the default gateway ip address.

Swapped private and public IP?

Hi,

I'm using your latest version of the package and I found a weirdo issue. Whenever I try to call the .address() API, I get swapped values. See the following snippet:

ip.address( 'private', 'ipv4' ) // 192.168.1.254
ip.address( 'public', 'ipv4' ) // 127.0.0.1

Why? Any help is really appreciated.

Thanks in advance!

Google Cloud External IP

How to know External IP of a Google compute engine where my NodeJs application running. all time it shows internal Ip

IPv6: Swapped private and public IP?

Related to: #57

It seems that the other issues tackled only the IPv4. This time also the IPv6 is affected by the same bug.

Can you please fix it? Please also publish to NPM when it's done.

Thank you in advance :)

`ip.address` returns a different address from `ipconfig` in Windows

When I run

var ip = require ("ip")
const deviceIp = ip.address()
console.log(deviceIp)

It prints a different address the IPv4 address that show on the ipconfig command. I must say that both addresses allow me to view the local server in the browser. What is the difference between those addresses? Why return a different value from the one IPconfig shows?

No need for regex to check for loopback anymore

The newer versions of node (see here) provide a new property called internal which can be used to detect internal addresses (i.e. loopback), so I would say isLoopback can be replaced with details.internal.

I know this might be minimal improvement, but I think its the first step in upgrading to the new os API.

Multiple addresses support

With the current implementation of address function, there is no possibility to retrieve multiple addresses assign to the interface. For configuration like this:

eth0: 
   [ { address: '10.0.2.15',
       netmask: '255.255.255.0',
       family: 'IPv4',
       mac: '08:00:27:88:0c:a6',
       internal: false },
     { address: '10.0.2.16',
       netmask: '255.255.255.0',
       family: 'IPv4',
       mac: '08:00:27:88:0c:a6',
       internal: false },
     { address: 'fe80::a00:27ff:fe88:ca6',
       netmask: 'ffff:ffff:ffff:ffff::',
       family: 'IPv6',
       mac: '08:00:27:88:0c:a6',
       scopeid: 2,
       internal: false } ] }

there is no possibility to gather both assign addresses (10.0.2.15 and 10.0.2.16).

IPv6 CIDR contains() returns true when it should return false

Here’s an example:

ip.cidrSubnet('2001:db8:f53b::/48').contains('2001:db8:f53a::1');
// returns: true, should return false

ip.cidrSubnet('2001:db8:f53b::/128').contains('2001:db8:f53a::1');
// returns: true, should return false

This seems obvious so, probably I’m using the library incorrectly, but I can’t see how to fix it.

subnet.contains returns true when it should return false

I am running Ubuntu 16.04 with node.js version 6.9.1

~$node
> var s = require('ip').subnet;
undefined
> var n = s('12.49.75.224', '12.49.75.227');
undefined
> n.contains('46.183.223.232');
true
>n
{ networkAddress: '12.49.75.224',
  firstAddress: '12.49.75.225',
  lastAddress: '12.49.75.226',
  broadcastAddress: '12.49.75.227',
  subnetMask: '12.49.75.227',
  subnetMaskLength: 30,
  numHosts: 2,
  length: 4,
  contains: [Function: contains] }
> 

Getting wrong private IP

Results provided from my shell

  Swap usage:   0%                IP address for eth1: 10.130.88.174

carousell@web-iso-3:~$ netstat -an | grep -E "5000|9200|8080"
tcp        0      0 10.15.0.151:8080        0.0.0.0:*               LISTEN

As you can see my application is not listening to eth1.

Shouldn't my application be listening to eth1 when I specify:

server.listen(
    server.get("port"),
   ip.address("private")
);

ip.cidrSubnet() returns IPv4 addresses when IPv6 addresses are provided.

The cidrSubnet() method returns IPv4 addresses for the {network,first,last,broadcast}Address when IPv6 addresses are provided:

> ip.cidrSubnet('2404:6800:4007:805::200e/56')
{ networkAddress: '0.0.9.100',
  firstAddress: '0.0.9.100',
  lastAddress: '0.0.9.99',
  broadcastAddress: '0.0.9.99',
  subnetMask: 'ffff:ffff:ffff:ff00::',
  subnetMaskLength: 56,
  numHosts: 5.960464477539063e-8,
  length: 5.960464477539063e-8,
  contains: [Function] }

Getting wrong IP address on Mac OS X 10.10.1

When I call ip.address() on Mac OS X 10.10.1 I am getting 127.94.0.1 which is device 'lo0'. The IP address of the machine is 192.168.* on device 'en0'. Am I mistaken in assuming it should be returning the local network IP? That's what I need to get.

FWIW I ran it on Linux and it is returning the 'eth0' device's address properly. So the bug appears to be Mac OS X 10.10.1 specific.

I am using ip 0.3.2

npm not serving the latest version

If you do npm install, the version of ip that you get does not have the latest changes. In particular, it doesn’t have the isPrivate() method.

Ip is giving single strings("1", "2") without dot as valid ipV6address.

ip.isV6Format("1") is returning true.

/^(::)?(((\d{1,3}.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/.test("1")
true

/^(::)?(((\d{1,3}.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/.test("12")
true

/^(::)?(((\d{1,3}.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/.test("123")
true

/^(::)?(((\d{1,3}.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/.test("1234")
true

cidrSubnet for ipv6 returns invalid result

is this module support for ipv6?

It seems that it return invalid results, for example

ip.cidrSubnet("2001:420:5a44::/48");
/*
{ networkAddress: '0.0.7.209',
     firstAddress: '0.0.7.209',
     lastAddress: '0.0.7.208',
     broadcastAddress: '0.0.7.208',
     subnetMask: 'ffff:ffff:ffff::',
     subnetMaskLength: 48,
     numHosts: 0.0000152587890625,
     length: 0.0000152587890625 }
*/

Not validating properly (IPV4 with block >= 256 still returns true)

Hi,

The methods ip.isV4Format() and ip.isV6Format() are returning true for an invalid IP address:

const ipAddress = "103.23.133.256";
console.log(ipAddress, ip.isV4Format(ipAddress), ip.isV6Format(ipAddress));
// > 103.23.133.256 true true

Should this not validate each block so that V4 blocks > 255 would case the function to return false? Also, since V4 and V6 addresses have different delimiters (colons/periods) that passing a V4 address into the isV6Format function should return false as well?

Would it be possible to add a validation method that accepts both V4 and V6 addresses and validates them?

Add isIP() method

I wish this module provided a function like isIP() to check if a string contains an IP address or not (hostname). Or.. maybe isValid() might be even better.

ip -> getMacAddress

Is there a way to getMacAddress using this module?
I tried macaddress npmjs but it can't install properly for me.

multiple IPs

How can I get my IPs from this configuration :

me@here:~/nodejs-projects/tim$ ifconfig

enp4s0 Link encap:Ethernet HWaddr 00:04:ac:f3:62:d0
inet addr:192.168.1.254 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::204:acff:fef3:62d0/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4900576 errors:0 dropped:0 overruns:0 frame:0
TX packets:3296566 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:4577415638 (4.5 GB) TX bytes:550292783 (550.2 MB)

enp4s5 Link encap:Ethernet HWaddr 00:15:17:5c:9e:55
inet addr:10.139.238.194 Bcast:10.139.238.223 Mask:255.255.255.224
inet6 addr: fe80::215:17ff:fe5c:9e55/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:4581022 errors:0 dropped:274 overruns:0 frame:0
TX packets:5786250 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:779326013 (779.3 MB) TX bytes:5233689092 (5.2 GB)

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:162008 errors:0 dropped:0 overruns:0 frame:0
TX packets:162008 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1
RX bytes:50482196 (50.4 MB) TX bytes:50482196 (50.4 MB)

[BUG] ip.isPrivate mocha test fail

BUG

mocha test fail.
ip.isPrivate return wrong result.

Repodruce

ip=require('./node_modules/ip')
ip.isPrivate(ip.address('private', 'IPV6'))

Expected

true

Behavior

false

Versions

Package version: 1.1.5
Runtime: nodejs v14.16.0 and v10.19.0 both fail.

Code Coverage

Running the tests with Istanbul indicates coverage at 89%.

node-ip-coverage-89

Would you accept a PR raising the coverage to 100%?

fromPrefixLen returns wrong result with PhantomJS

Hi,
I was trying to use ip.fromPrefixLen(20) function, but it gives me -1.-1.-1.-256 as a result.
It is happening only with PhantomJS testing, when I use it with a "normal" browser, it works perfectly.

Support for IPv6 mapped IPv4 addresses

Ip module doesn't seem to support IPv6 addresses that contain mapped IPv4 address? This is odd as in dual-stack case that's what methods from net module return.

      "Error: Invalid ip address: ::ffff:201.51.40.12",
      "    at Error (native)",
      "    at Object.toBuffer (/home/mas/mas/node_modules/ip/lib/ip.js:38:40)",
      "    at Object.isEqual (/home/mas/mas/node_modules/ip/lib/ip.js:229:10)"

Is valid ip

Is there a way to check if a given string is a valid ip using this library?

For example:

const ip = require('ip');
ip.isValid('google.com'); // false
ip.isValid('216.58.194.206'); // true
ip.isValid('2607:f8b0:4005:804::200e'); // true

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.