SoFunction
Updated on 2025-03-09

Simple example of detecting whether the port is occupied

Preface

In network technology, ports (Ports) have roughly two meanings: one is ports in the physical sense, such as the interfaces used by ADSL Modem, hubs, switches, and routers to connect to other network devices, such as RJ-45 ports, SC ports, etc. The second is a port in the logical sense, which generally refers to the port in the TCP/IP protocol. The port number ranges from 0 to 65535, such as for browsing web services. The purpose of this article is to solve the problem that the port is occupied when the SSL tool is used for multiple services. Below is a code snippet of research. If you need it, you can refer to it.

Sample code

// Check whether the port is occupiedfunction probe(port, callback) {

  var server = ().listen(port)

  var calledOnce = false

  var timeoutRef = setTimeout(function () {
    calledOnce = true
    callback(false,port)
  }, 2000)

  ()

  var connected = false

  ('listening', function() {
    clearTimeout(timeoutRef)

    if (server)
      ()

    if (!calledOnce) {
      calledOnce = true
      callback(true,port)
    }
  })

  ('error', function(err) {
    clearTimeout(timeoutRef)

    var result = true
    if ( === 'EADDRINUSE')
      result = false

    if (!calledOnce) {
      calledOnce = true
      callback(result,port)
    }
  })
}

function server(_port){
  var pt = _port || __port;
  probe(pt,function(bl,_pt){
    // Port is occupied bl Return false    // _pt: the incoming port number    if(bl === true){
      // ssr(_pt)
      server = (connListener);
      server = (parseInt(_pt, 10));
      ("\n Static file server running at" + "\n\n=> http://localhost:" + _pt + '\n');
    }else{
      server(_pt+1)
    }
  })
}

Summarize

The above is the entire content of this article. I hope it will help you study or work. If you have any questions, you can leave a message to communicate.