Port Scanning and Service Status Checking in PHP
By Akash Mehta2008-06-06
Service Checking 101
We will be using the PHP function fsockopen() to attempt to open
a connection to the port we want to check. If the connection fails, the function
will return false. The function also has options to return an error
number and an error string if the connection fails. However, a connection does
not technically "fail" in a network - or, at least, that is not what we are
checking. If the service is offline, the server will simply not respond to the
connection and the connection will timeout. We specify how long we want
to wait till the connection is considered timed out using a parameter to the
function.
Fire up your favourite text editor and copy in the following:
<?php
$connection = @fsockopen("www.google.com", 80);
if ($connection) {
echo "Port 80 on www.google.com is open.";
fclose($connection);
} else {
echo "Port 80 on www.google.com is not open.";
}
In this snippet, we call fsockopen and ask it to open a
connection to "www.google.com" on port 80. If the connection is established -
fsockopen indicates this by returning a non-false value - we
display an appropriate status message, and likewise if the connection is not
established. In a variety of situations, the function will output an error
message, and so we use the @ symbol before the function name to suppress errors
generated.
The function actually returns a handle on a socket connection
established, a reference by which you can tell the other socket functions to
manipulate this particular connection. In this case, if the connection is
established, we need to close the connection, or we could soon overload the
server (ours, and theirs!) with an excess of open connections. We achieve this
using the fclose function.
Port scanning
As this method is simply checking a particular port on the server, we can easily scan for a number of ports on the server using a simple for loop. This method is known as port scanning. Often a server will be running a range of web-facing services, and server scanning allows server operators to scan for services they may not be aware of. Any web-facing software can bring with it additional security risks, and so port scanning is a popular part of security testing. If we wanted to check all the ports between 1 and 1000 on localhost, we could do this with just a few lines of code:
<?php
for($i=1;$i<=1000;$i++) {
$conn = @fsockopen("localhost", $i);
if ($conn) {
echo "Port $i is open.\n";
fclose($conn);
}
}
A simple yet effective implementation.
Tutorial Pages:
» Introduction
» Service Checking 101
» Our Implementation
» Advanced Status Checking
