How to verify that a service is listening on TCP using Node.js?

Summary . How can I use Node.js to find out if something is listening on a given port?

More details :

I am writing tests for an HTTP application in Node.

I expanded Node http.Serverwith util.inherits, and in the resulting "class" completes the standard functionality .listen()in my own name method .start(). This method does some tweaking (for example, connects to MongoDB) and then calls http.Server.listen(port, cb)when everything is going well.

My problem: I want to write a test that calls .start()and then checks to see if the server is really listening on the specified port. I would like to do this without sending an HTTP request to the server. I just want to check that the server is listening.

Unfortunately, I am not familiar with TCP, but, given my experience with port scans and netstatsomething like that, I got the impression that something in Node net would allow me to do this. Is it possible?

+2
source share
3 answers

Use net.connect ():

var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
  console.log('client connected');
  client.end();
});

Node.JS module documentationnet

+7
source

, node.js, , - , :

, TCP-. SYN, , . SYN/ACK , (), RST (reset) .

nmap, TCP/IP, , -.

+3

? , - , . , . " , ". . , , - .

+2

Source: https://habr.com/ru/post/1612802/


All Articles