24
2011
Make a TCP Connect port scanner in PHP
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.
Popularity: 2% [?]
Related Posts
Leave a comment
Subscribe
Recent Posts
- Login into phpmyadmin without username and password
- 10+ tips to localise your php application
- 40+ Techniques to enhance your php code – Part 3
- 40+ Techniques to enhance your php code – Part 2
- 40+ Techniques to enhance your php code – Part 1
- CSSDeck – Collection of Pure CSS Creations
- Execute shell commands in PHP
- Php get list of locales installed on system
- Sound cracking in Ubuntu 11.10
- PHP script to perform IP whois
An article by




