Code a TCP Connect port scanner in PHP

0 Flares Filament.io 0 Flares ×

A port scanner is a software application designed to probe a server or host for open ports. We earlier made a TCP Connect port scanner in C here - http://www.binarytides.com/blog/tcp-connect-port-scanner-code-in-c-with-winsock/

and here - http://www.binarytides.com/blog/tcp-connect-port-scanner-with-linux-sockets-bsd/

Now we shall try making the same 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.

Last Updated On : 19th November 2012

Subscribe to get updates delivered to your inbox

About Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at m00n.silv3r@gmail.com. Or find him on

  • materr

    And what can I do with the port if it happens to be open on a remote machine?

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 StumbleUpon 0 Filament.io 0 Flares ×