Path: blob/trunk/javascript/selenium-webdriver/net/portprober.js
1864 views
// Licensed to the Software Freedom Conservancy (SFC) under one1// or more contributor license agreements. See the NOTICE file2// distributed with this work for additional information3// regarding copyright ownership. The SFC licenses this file4// to you under the Apache License, Version 2.0 (the5// "License"); you may not use this file except in compliance6// with the License. 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,11// software distributed under the License is distributed on an12// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13// KIND, either express or implied. See the License for the14// specific language governing permissions and limitations15// under the License.1617'use strict'1819const net = require('node:net')2021/**22* Tests if a port is free.23* @param {number} port The port to test.24* @param {string=} opt_host The bound host to test the {@code port} against.25* Defaults to {@code INADDR_ANY}.26* @return {!Promise<boolean>} A promise that will resolve with whether the port27* is free.28*/29function isFree(port, opt_host) {30return new Promise((resolve, reject) => {31const server = net.createServer().on('error', function (e) {32if (e.code === 'EADDRINUSE' || e.code === 'EACCES') {33resolve(false)34} else {35reject(e)36}37})3839server.listen(port, opt_host, function () {40server.close(() => resolve(true))41})42})43}4445/**46* @param {string=} opt_host The bound host to test the {@code port} against.47* Defaults to {@code INADDR_ANY}.48* @return {!Promise<number>} A promise that will resolve to a free port. If a49* port cannot be found, the promise will be rejected.50*/5152function findFreePort(opt_host) {53return new Promise((resolve, reject) => {54const server = net.createServer()55server.on('listening', function () {56resolve(server.address().port)57server.close()58})59server.on('error', (e) => {60if (e.code === 'EADDRINUSE' || e.code === 'EACCES') {61resolve('Unable to find a free port')62} else {63reject(e)64}65})66// By providing 0 we let the operative system find an arbitrary port67server.listen(0, opt_host)68})69}7071// PUBLIC API72module.exports = {73findFreePort,74isFree,75}767778