# net/index.js

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