How to implement a port scanner using some scripting language?

5.57K viewsProgramminghacking nodejs port programming scanner

How to implement a port scanner using some scripting language?

Answered question

We can use any scripting language like python,perl,php etc. to achieve this. The idea is to create a socket on a port range and try to connect it. If connection allowed, means that particular port is open. If not, means the port is closed. Below is a nodeJS version of a port scanner trying to scan ports from number 1 to 10000.

(function() {
 var net = require('net');
  // the machine to scan
 var host = 'localhost';
 // starting from port number
 var start = 1;
 // to port number
 var end = 10000;
 // sockets should timeout asap to ensure no resources are wasted
 // but too low a timeout value increases the likelyhood of missing open sockets, so be careful
 var timeout = 2000;
  // the port scanning loop 
 while (start <= end) {
     // it is always good to give meaningful names to your variables
  // since the context is changing, we use <code>port</code> to refer to current port to scan 
  var port = start;
     // we create an anonynous function, pass the current port, and operate on it
  // the reason we encapsulate the socket creation process is because we want to preseve the value of <code>port</code> for the callbacks 
  (function(port) {
   // console.log('CHECK: ' + port);
   var s = new net.Socket();
       s.setTimeout(timeout, function() { s.destroy(); });
   s.connect(port, host, function() {
    console.log('OPEN: ' + port);
    // we don't destroy the socket cos we want to listen to data event
    // the socket will self-destruct in 2 secs cos of the timeout we set, so no worries
       // if any data is written to the client on connection, show it
   s.on('data', function(data) {
    console.log(port +': '+ data);
       s.on('error', function(e) {
    // silently catch all errors - assume the port is closed

Install node.js from node website here . Save the above code in a js file and run the above from command prompt using
Below is a sample output of the above script:

OPEN: 445
OPEN: 443
OPEN: 1026
OPEN: 1027
OPEN: 1031
OPEN: 1025
OPEN: 1032
OPEN: 1034
OPEN: 1338
OPEN: 1339
OPEN: 2701
2701: ” ? S T A R T _ H A N D S H A K E
OPEN: 3389
OPEN: 5357

Answered question
You are viewing 1 out of 2 answers, click here to view all answers.
Write your answer.