# 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    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}575859// PUBLIC API606162/**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 */67exports.getAddress = function(opt_family) {68  return getAddress(false, opt_family);69};707172/**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 */77exports.getLoopbackAddress = function(opt_family) {78  return getAddress(true, opt_family);79};