# net/index.js

    1// Copyright 2013 Selenium committers2// Copyright 2013 Software Freedom Conservancy3//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 at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// 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 and14// limitations under the License.1516'use strict';1718var os = require('os');192021function 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}303132/**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 */38function getAddress(loopback, opt_family) {39  var family = opt_family || 'IPv4';40  var addresses = [];4142  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}585960// PUBLIC API616263/**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 */68exports.getAddress = function(opt_family) {69  return getAddress(false, opt_family);70};717273/**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 */78exports.getLoopbackAddress = function(opt_family) {79  return getAddress(true, opt_family);80};