# net/index.js

1 | // Licensed to the Software Freedom Conservancy (SFC) under one
2 | // or more contributor license agreements. See the NOTICE file
3 | // distributed with this work for additional information
4 | // regarding copyright ownership. The SFC licenses this file
5 | // to you under the Apache License, Version 2.0 (the
6 | // "License"); you may not use this file except in compliance
7 | // with the License. You may obtain a copy of the License at
8 | //
9 | // http://www.apache.org/licenses/LICENSE-2.0
10 | //
11 | // Unless required by applicable law or agreed to in writing,
12 | // software distributed under the License is distributed on an
13 | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 | // KIND, either express or implied. See the License for the
15 | // specific language governing permissions and limitations
16 | // under the License.
17 |
18 | 'use strict';
19 |
20 | var os = require('os');
21 |
22 |
23 | function getLoInterface() {
24 | var name;
25 | if (process.platform === 'darwin') {
26 | name = 'lo0';
27 | } else if (process.platform === 'linux') {
28 | name = 'lo';
29 | }
30 | return name ? os.networkInterfaces()[name] : null;
31 | }
32 |
33 |
34 | /**
35 | * Queries the system network interfaces for an IP address.
36 | * @param {boolean} loopback Whether to find a loopback address.
37 | * @param {string=} opt_family The IP family (IPv4 or IPv6). Defaults to IPv4.
38 | * @return {string} The located IP address or undefined.
39 | */
40 | function getAddress(loopback, opt_family) {
41 | var family = opt_family || 'IPv4';
42 | var addresses = [];
43 |
44 | var interfaces;
45 | if (loopback) {
46 | var lo = getLoInterface();
47 | interfaces = lo ? [lo] : null;
48 | }
49 | interfaces = interfaces || os.networkInterfaces();
50 | for (var key in interfaces) {
51 | interfaces[key].forEach(function(ipAddress) {
52 | if (ipAddress.family === family &&
53 | ipAddress.internal === loopback) {
54 | addresses.push(ipAddress.address);
55 | }
56 | });
57 | }
58 | return addresses[0];
59 | }
60 |
61 |
62 | // PUBLIC API
63 |
64 |
65 | /**
66 | * Retrieves the external IP address for this host.
67 | * @param {string=} opt_family The IP family to retrieve. Defaults to "IPv4".
68 | * @return {string} The IP address or undefined if not available.
69 | */
70 | exports.getAddress = function(opt_family) {
71 | return getAddress(false, opt_family);
72 | };
73 |
74 |
75 | /**
76 | * Retrieves a loopback address for this machine.
77 | * @param {string=} opt_family The IP family to retrieve. Defaults to "IPv4".
78 | * @return {string} The IP address or undefined if not available.
79 | */
80 | exports.getLoopbackAddress = function(opt_family) {
81 | return getAddress(true, opt_family);
82 | };