Giter Site home page Giter Site logo

network's Introduction

Network Utilies for Node.js

Install

$ npm install network

Usage

Get public IP

Returns your public IP address, as reported by DynDNS.org or other services.

var network = require('network');

network.get_public_ip(function(err, ip) {
  console.log(err || ip); // should return your public IP address
})
CLI
$ network public_ip

Get private IP

Returns the IP address assigned to your first active network inteface.

network.get_private_ip(function(err, ip) {
  console.log(err || ip); // err may be 'No active network interface found'.
})
CLI
$ network private_ip

Get gateway IP

Returns the IP of the gateway that your active network interface is linked to.

network.get_gateway_ip(function(err, ip) {
  console.log(err || ip); // err may be 'No active network interface found.'
})
CLI
$ network gateway_ip

Get active interface

Returns the IP, MAC address and interface type for the active network interface. On OS X and Linux you also get the IP of its assigned gateway.

network.get_active_interface(function(err, obj) {

  /* obj should be:

  { name: 'eth0',
    ip_address: '10.0.1.3',
    mac_address: '56:e5:f9:e4:38:1d',
    type: 'Wired',
    netmask: '255.255.255.0',
    gateway_ip: '10.0.1.1' }

  */
})
CLI
$ network active_interface

Get interfaces list

Returns list of network interfaces, including MAC addresses and the such, just as in the example above.

network.get_interfaces_list(function(err, list) {

  /* list should be:

  [{
    name: 'eth0',
    ip_address: '10.0.1.3',
    mac_address: '56:e5:f9:e4:38:1d',
    type: 'Wired',
    netmask: '255.255.255.0',
    gateway_ip: '10.0.1.1' 
   },
   { ... }, { ... }]

  */
})
CLI
$ network interfaces_list

Copyright

Written by Tomás Pollak. Copyright (c) Fork, Ltd.

License

MIT.

network's People

Contributors

fttx avatar kokarn avatar kootoopas avatar lwintermelon avatar melvinto avatar penguinpowernz avatar talb2005 avatar theboolean avatar theworkflow avatar tigerbot avatar tomas avatar voidvolker 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

network's Issues

Missing netmask attribute in get_interfaces_list on Windows

Hi @tomas, thank you for this library!
It's working like a charm for my project on Linux, but today I started some cross platform compatibility tests and found it behave differently on Windows. Interfaces are missing netmask attribute when listed by get_interfaces_list.
BTW I found the problem and I'm making a PR to fix it.

Can't get a IP address

Hi, I can't get a certain IP address, got a 'undefined' instead :)
After I dive into the source code,I found that os.networkInterfaces() returned a weried NetConnectionID(yes, it's on Windows 7) with "????",actually is "本地连接"。So,in my guess,it's a case of string encoding,however, I don't know how dose this happen.

Wrong NetMask shown for IP

Node: 6.9.1
network: 0.4.0

I have this situation where eth0 has two IP addresses (one assigned by DHCP and the other is a link-local address assigned by systemd-networkd), but get_interfaces_list() returns the IP of the DHCP address with the netmask of the link-local address.

{
  "name": "eth0",
  "ip_address": "192.168.2.116",
  "mac_address": "5c:f8:21:0f:40:d8",
  "gateway_ip": "192.168.2.1",
  "netmask": "255.255.0.0",
  "type": "Wired"
}

Output from os.networkInterfaces()

> os.networkInterfaces()
{ lo:
   [ { address: '127.0.0.1',
       netmask: '255.0.0.0',
       family: 'IPv4',
       mac: '00:00:00:00:00:00',
       internal: true } ],
  eth0:
   [ { address: '169.254.123.48',
       netmask: '255.255.0.0',
       family: 'IPv4',
       mac: '5c:f8:21:0f:40:d8',
       internal: false },
     { address: '192.168.2.116',
       netmask: '255.255.255.0',
       family: 'IPv4',
       mac: '5c:f8:21:0f:40:d8',
       internal: false } ] }

Output from ip -o -4 addr show eth0:

2: eth0    inet 169.254.123.48/16 brd 169.254.255.255 scope link eth0\       valid_lft forever preferred_lft forever
2: eth0    inet 192.168.2.116/24 brd 192.168.2.255 scope global dynamic eth0\       valid_lft 1803687sec preferred_lft 1803687sec

This also poses the question: How can I grab a specific IP address for an interface using network? In my application for example, I am interested in the scope global address when available, otherwise in the scope local address.

Depends on ifconfig

I tried to use this package inside docker and it couldn't find the active interface.

It turns out it is dependent on ifconfig and I had to install net-tools to make it work.

Checking if ifconfig is available during the installation and warning would be good!

Crash on RaspberryPi

On raspberry with node version 10.6.0, I have the error :
/home/pi/rdr/node_modules/network/lib/linux.js:87
nics[key].forEach(function(type) {
^

TypeError: nics[key].forEach is not a function
at Object.exports.get_network_interfaces_list (/home/pi/rdr/node_modules/network/lib/linux.js:87:17)
at nic_by_name (/home/pi/rdr/node_modules/network/lib/index.js:21:16)
at /home/pi/rdr/node_modules/network/lib/index.js:98:5
at /home/pi/rdr/node_modules/network/lib/linux.js:26:5
at ChildProcess.exithandler (child_process.js:282:7)
at ChildProcess.emit (events.js:182:13)
at maybeClose (internal/child_process.js:961:16)
at Socket.stream.socket.on (internal/child_process.js:380:11)
at Socket.emit (events.js:182:13)
at Pipe._handle.close (net.js:598:12)

To make it work, just change line 87:

nics[key].forEach(function(type) {
if (type.family == 'IPv4') {
obj.ip_address = type.address;
}
});

TO :

Object.keys(nics[key]).forEach(function(type) {
if (type.family == 'IPv4') {
obj.ip_address = type.address;
}
});

get_active_interface doesn't work on Mac OS Catalina 10.15.2

Throws error

No active interfaces detected.

I've tracked the issue down to the function 'get_active_network_interface_name'.
var cmd = "netstat -rn | grep UG | awk '{print $6}'";
running this command on my Mac returns an empty string.

I noticed that in linux.js the command is var cmd = "netstat -rn | grep UG | awk '{print $NF}'";
Perhaps it should be the same for darwin.js?

Calling get_interfaces_list on Windows 7 does not return the ip address

The examples show the array containing objects with the ip addresses, but it does not return it on Windows for a wireless interface (Intel Centurion Advanced-N 6230. It does have the Mac/Name/Model/Vendor/Type.

Moreover the active interface for the wireless interface doesn't return anything from network.get_active_interface.

Doing ipconfig show me that the interface as an IP address.

Update `needle` dependency

With the current version of needle listed in the package.json, when DEBUG is set needle will console.log any content.

Get Default Gateway macOS

On macOS the get default gateway script dose not work.

network.get_gateway_ip(function(err, ip) {
  console.log(err || ip); // err may be 'No active network interface found.'
})

This is because the command ipconfig getoption en0 router dose not work on macOS

Here is the error:

Error: Command failed: ipconfig getoption en0 router

    at ChildProcess.exithandler (child_process.js:308:12)
    at ChildProcess.emit (events.js:314:20)
    at maybeClose (internal/child_process.js:1047:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5) {
  killed: false,
  code: 1,
  signal: null,
  cmd: 'ipconfig getoption en0 router'
}

new method to get hostnames

It would be worth having a method like network.get_hostnames(cb), that returns a map Hostname <--> IP for the current active interface? (parsing the output of arp -a on unix).

Expose gateway_ip_for

It would be nice to be able to specify which interface you want to get the gateway IP for. What are your thoughts on this? I could open a PR.

Create a separate module for CLI

The idea would be to create a different module for the CLI. Like network-cli
So this is used as dependency and we can get rid of commander package, if someone want to use this programmatically.

Get Active Interface Issue

I was on WiFi Network in my Windows 10, get active interface returns the Ethernet interface instead of WiFi interface.

Error: Encoding not recognized: 'cp720' (searched as: 'cp720')

When call below func on the Windows 10 :

network.get_interfaces_list(function(err, list) {
    console.log(err || list);
})

---Error----------------------

\network\node_modules\iconv-lite\lib\index.js:106
                throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
                ^

Error: Encoding not recognized: 'cp720' (searched as: 'cp720')
    at Object.getCodec (F:\Example-Project\network\node_modules\iconv-lite\lib\index.js:106:23)
    at Object.getDecoder (F:\Example-Project\network\node_modules\iconv-lite\lib\index.js:127:23)
    at Object.decode (F:\Example-Project\network\node_modules\iconv-lite\lib\index.js:40:25)
    at F:\Example-Project\network\node_modules\wmic\index.js:228:20
    at Array.map (<anonymous>)
    at stringifyBufferArray (F:\Example-Project\network\node_modules\wmic\index.js:227:18)
    at F:\Example-Project\network\node_modules\wmic\index.js:214:25
    at err (F:\Example-Project\network\node_modules\wmic\node_modules\async\dist\async.js:2939:19)
    at wrapper (F:\Example-Project\network\node_modules\wmic\node_modules\async\dist\async.js:270:20)
    at iteratorCallback (F:\Example-Project\network\node_modules\wmic\node_modules\async\dist\async.js:497:17)

Error: No Instance(s) Available.

Hi, can you help me, with this issue: on windows i found that when any method try found any info (like os_functions.netmask_for etc.) by "nic_name" it throws "Error: No Instance(s) Available."
I found this bug because of my system encoding is not 'utf8' and recive information in wrong encoding.

Is there any simple decision?

Mask bug

Hi!
code:

var network = require('network');
network.get_active_interface(function(err, obj) {
console.log(obj);
});

result is:

root@raspbx:~/siren# node test
{ name: 'eth0',
ip_address: '192.168.88.174',
mac_address: 'b8:27:eb:a8:b4:7a',
gateway_ip: '192.168.88.1',
netmask: 'Mask:255.255.255.0' } //WTF?? netmask: 'Mask ?

os Raspbian 8.0
nodejs v7.1.0
Thanks!

EMFILE: too many open files

I call the module as here:

 function _whichIface()
{
	net.get_interfaces_list(function(err,list){

		 _(list).forEach(function(element){
		 	if	(element.name)
		 	{
		 		if (element.name == "ppp0")
		 		{
		 			rpio.blink("led3G",-2);//pulse
		 		
		 		}
		 		if (element.name == "wlan0")
		 		{
		 			rpio.blink("ledWifi",-2);//pulse
		 			
		 		}
		 	}
		 });
	}); 
}

BUt sometimes I get:

{ Error: EMFILE: too many open files, uv_interface_addresses
    at Error (native)
    at Object.exports.get_network_interfaces_list [as get_interfaces_list] (/node_modules/network/lib/linux.js:54:17)

Wrong IP

wlan0     Link encap:Ethernet  HWaddr b8:27:eb:a5:16:d4  
          inet addr:192.168.1.149  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::e1bf:48cf:786c:ee08/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:48895 errors:0 dropped:71 overruns:0 frame:0
          TX packets:28059 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:17395152 (16.5 MiB)  TX bytes:13433226 (12.8 MiB)

root@casa# node
> var net = require('network');
> net.get_interfaces_list(function(err, list) {console.log(list)})

> [ { name: 'wlan0',
    ip_address: '169.254.126.229',
    mac_address: 'b8:27:eb:a5:16:d4',
    gateway_ip: '192.168.1.254',
    netmask: '255.255.255.0',
    type: 'Wireless' } ]

Return broadcast ip

Could you add the broadcast IP to the return information for active_interface?

Here is some not so pretty code that I found and modified.

function IPv4_Address( addressDotQuad, netmaskDotQuad ) {
var addressInteger = IPv4_dotquad_to_int( addressDotQuad.toString() );
var addressBinStr = IPv4_int_to_binstr( addressInteger );

var netmaskInteger = IPv4_dotquad_to_int( netmaskDotQuad.toString() );
var netmaskBinStr  = IPv4_int_to_binstr( netmaskInteger );

var netbcastBinStr = IPv4_calc_netbcastBinStr( addressBinStr, netmaskBinStr );
var netbcastInteger = IPv4_binstr_to_int( netbcastBinStr );	

return IPv4_int_to_dotquad( netbcastInteger );

}

/* dotted-quad IP to integer /
function IPv4_dotquad_to_int( strbits ) {
var split = strbits.split( '.', 4 );
var myInt = (
parseFloat( split[0] * 16777216 ) /
2^24 /
+ parseFloat( split[1] * 65536 ) /
2^16 /
+ parseFloat( split[2] * 256 ) /
2^8 */
+ parseFloat( split[3] )
);
return myInt;
}

/* integer IP to binary string representation /
function IPv4_int_to_binstr( strnum ) {
var numStr = strnum.toString( 2 ); /
Initialize return value as string /
var numZeros = 32 - numStr.length; /
Calculate no. of zeros */
if (numZeros > 0) {
for (var i = 1; i <= numZeros; i++) {
numStr = "0" + numStr
}
}
return numStr;
}

/* logical OR between address & NOT netmask /
function IPv4_calc_netbcastBinStr( addressBinStr, netmaskBinStr ) {
var netbcastBinStr = '';
var aBit = 0; var nmBit = 0;
for( pos = 0; pos < 32; pos ++ ) {
aBit = parseInt( addressBinStr.substr( pos, 1 ));
nmBit = parseInt( netmaskBinStr.substr( pos, 1 ));
if( nmBit ) {
nmBit = 0; /
flip netmask bits */
} else {
nmBit = 1;
}
if( aBit || nmBit ) {
netbcastBinStr += '1';
} else {
netbcastBinStr += '0';
}
}
return netbcastBinStr;
}

/* binary string IP to integer representation */
function IPv4_binstr_to_int( binstr ) {
return parseInt( binstr, 2 );
}

/* integer IP to dotted-quad */
function IPv4_int_to_dotquad( strnum ) {
var byte1 = ( strnum >>> 24 );
var byte2 = ( strnum >>> 16 ) & 255;
var byte3 = ( strnum >>> 8 ) & 255;
var byte4 = strnum & 255;
return ( byte1 + '.' + byte2 + '.' + byte3 + '.' + byte4 );
}

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.