11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ci// Skip test in FreeBSD jails
41cb0ef41Sopenharmony_ciif (common.inFreeBSDJail)
51cb0ef41Sopenharmony_ci  common.skip('In a FreeBSD jail');
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciconst assert = require('assert');
81cb0ef41Sopenharmony_ciconst net = require('net');
91cb0ef41Sopenharmony_ci
101cb0ef41Sopenharmony_cilet conns = 0;
111cb0ef41Sopenharmony_ciconst clientLocalPorts = [];
121cb0ef41Sopenharmony_ciconst serverRemotePorts = [];
131cb0ef41Sopenharmony_ciconst client = new net.Socket();
141cb0ef41Sopenharmony_ciconst server = net.createServer((socket) => {
151cb0ef41Sopenharmony_ci  serverRemotePorts.push(socket.remotePort);
161cb0ef41Sopenharmony_ci  socket.end();
171cb0ef41Sopenharmony_ci});
181cb0ef41Sopenharmony_ci
191cb0ef41Sopenharmony_ciserver.on('close', common.mustCall(() => {
201cb0ef41Sopenharmony_ci  // Client and server should agree on the ports used
211cb0ef41Sopenharmony_ci  assert.deepStrictEqual(serverRemotePorts, clientLocalPorts);
221cb0ef41Sopenharmony_ci  assert.strictEqual(conns, 2);
231cb0ef41Sopenharmony_ci}));
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ciserver.listen(0, common.localhostIPv4, connect);
261cb0ef41Sopenharmony_ci
271cb0ef41Sopenharmony_cifunction connect() {
281cb0ef41Sopenharmony_ci  if (conns === 2) {
291cb0ef41Sopenharmony_ci    server.close();
301cb0ef41Sopenharmony_ci    return;
311cb0ef41Sopenharmony_ci  }
321cb0ef41Sopenharmony_ci
331cb0ef41Sopenharmony_ci  conns++;
341cb0ef41Sopenharmony_ci  client.once('close', connect);
351cb0ef41Sopenharmony_ci  assert.strictEqual(
361cb0ef41Sopenharmony_ci    client,
371cb0ef41Sopenharmony_ci    client.connect(server.address().port, common.localhostIPv4, () => {
381cb0ef41Sopenharmony_ci      clientLocalPorts.push(client.localPort);
391cb0ef41Sopenharmony_ci    })
401cb0ef41Sopenharmony_ci  );
411cb0ef41Sopenharmony_ci}
42