How to Code a TCP Connect Port Scanner in PHP

By | August 11, 2020

A port scanner is a program designed to probe a server or host for open ports. Looking at open ports, one can tell what services might be running on the remote server.

We earlier made a TCP Connect port scanner in C here - https://www.binarytides.com/tcp-connect-port-scanner-code-c-winsock/

and here - https://www.binarytides.com/tcp-connect-port-scanner-c-code-linux-sockets/

Now we shall try making the same port scanner in PHP.
The code is very simple:

Using fsockopen

<?php
/*
  Simple TCP connect port scanner in php using fsockopen
*/

//avoid warnings like this PHP Warning:  fsockopen(): unable to connect to 192.168.1.2:83 (Connection refused) in /var/www/blog/port_scanner.php on line 10
error_reporting(~E_ALL);

$from = 1;
$to = 255;

//TCP ports
$host = '192.168.1.2';

for($port = $from; $port <= $to ; $port++)
{
  $fp = fsockopen($host , $port);
  if ($fp)
  {
    echo "port $port open \n";
    fclose($fp);
  }	 
}

Output :

desktop:~$ php /var/www/blog/port_scanner.php 
port 21 open 
port 22 open 
port 80 open

The above code uses fsockopen to connect a host on a port , and if the connection is established then it returns true , indicating that the port is open.

Using PHP Sockets

/*
  Simple TCP connect port scanner in php using fsockopen
*/

//avoid warnings PHP Warning:  fsockopen(): unable to connect to 192.168.1.2:83 (Connection refused) in /var/www/blog/port_scanner.php on line 10
error_reporting(~E_ALL);

$from = 1;
$to = 255;

//TCP ports
$host = '192.168.1.2';

//Create a socket
$socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP);  
for($port = $from; $port <= $to ; $port++)
{
    //connect to the host and port
    $connection = socket_connect($socket , $host ,  $port);
    if ($connection)
    {
      echo "port $port open \n";
      
      //Close the socket connection
      socket_close($socket);

      //Create a new since earlier socket was closed , we need to close and recreate only when a connection is made
      //otherwise we can use the same socket
      $socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP);  
    }	 
}

Output :

desktop:~$ php /var/www/blog/port_scanner.php 
port 21 open 
port 22 open 
port 80 open

The above example uses the php socket functions socket_create and socket_connect , to connect to a host on a port.

If the connection is established the socket_connect function returns true , indicating that the port is open.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

2 Comments

How to Code a TCP Connect Port Scanner in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *