| 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 | interfaces = [getLoInterface()]; |
| 45 | } |
| 46 | interfaces = interfaces || os.networkInterfaces(); |
| 47 | for (var key in interfaces) { |
| 48 | interfaces[key].forEach(function(ipAddress) { |
| 49 | if (ipAddress.family === family && |
| 50 | ipAddress.internal === loopback) { |
| 51 | addresses.push(ipAddress.address); |
| 52 | } |
| 53 | }); |
| 54 | } |
| 55 | return addresses[0]; |
| 56 | } |
| 57 | |
| 58 | |
| 59 | // PUBLIC API |
| 60 | |
| 61 | |
| 62 | /** |
| 63 | * Retrieves the external IP address for this host. |
| 64 | * @param {string=} opt_family The IP family to retrieve. Defaults to "IPv4". |
| 65 | * @return {string} The IP address or undefined if not available. |
| 66 | */ |
| 67 | exports.getAddress = function(opt_family) { |
| 68 | return getAddress(false, opt_family); |
| 69 | }; |
| 70 | |
| 71 | |
| 72 | /** |
| 73 | * Retrieves a loopback address for this machine. |
| 74 | * @param {string=} opt_family The IP family to retrieve. Defaults to "IPv4". |
| 75 | * @return {string} The IP address or undefined if not available. |
| 76 | */ |
| 77 | exports.getLoopbackAddress = function(opt_family) { |
| 78 | return getAddress(true, opt_family); |
| 79 | }; |