Adding Methods to the Query Processor in PHP

Over this second article in a series covering network programming in PHP, you will learn how to run popular Windows network monitoring utilities, such as the “ping,” “netstat” and “ipconfig” programs, by adding some new methods to the “QueryProcessor” class introduced in the previous article.

Introduction

Want to learn more about the basics of network programming in PHP? Look no further. Welcome to the second part of the series “Network Programming in PHP.” This set of three tutorials teaches how to use numerous networking PHP built-in functions in a practical way, in order to build a query processor in PHP 5, which can be used to perform some of the most common network operations.

As usual, I’d like to step back for a moment to the previous article of the series, and refresh your memory of some of the topics that I explored in that tutorial. In this way, you’ll be able to pick up the flow of the concepts that I’ll deploy in the next few lines, without needing to reread the prior article.

As you’ll probably recall, in the first part of the series, I went through the basics of using many native PHP functions included in its networking library, and started constructing an extensible query processor class in PHP 5. During this coding experience, you hopefully learned how convert host names to their corresponding IP addresses and vice versa, how to find the number of a given TCP port that is used by a specific service, and how to list the services in conjunction with their corresponding port numbers.

Even though most of these tasks can be considered trivial operations, they should be taken into account as an introductory and educational exercise, useful for tackling more complex PHP projects that require the implementation of advanced network programming routines. This might eventually include working with low-level sockets, handling DNS records, reading and writing socket streams, and so forth.

Right, at this point I guess that all the networking PHP built-in functions that I covered in the first article, such as the “gethostbyaddr()”, “gethostbyname()”, “gethostbynamel()” functions are already familiar to you. So now I will explain what new things you’ll learn in this second article of the series. Since I want to continue expanding the “QueryProcessor” class that I coded previously, this installment will focus on adding more methods to it, by using other useful PHP network functions, aimed particularly at running popular Windows networking applications, like “ipconfig,” “netstat” and more.

Having established the goals for this article, let’s move on and see how the “QueryProcessor” class can be expanded by aggregating more network-based methods. Let’s get started.

{mospagebreak title=Reviewing previous PHP networking functions: a quick look at the “QueryProcessor” class}

Before I proceed to add some additional methods to the PHP 5 “QueryProcessor” class that you saw previously, allow me first to list its source code, as it was defined originally in the first article. Here is the signature for the “QueryProcessor” class:

class QueryProcessor{
    private $host;
    private $services=array
(‘http’,’https’,’ftp’,’telnet’,’imap’,’smtp’,’nicname’,’gopher’,
‘finger’,’pop3′,’www’);
    private $ports=array(21,23,25,43,70,79,80,110,143,443);
    public function __construct($host=’myhost.com’){
        $this->host=$host;
    }
    // get IP address
    public function getIp(){
        if(!$ip=gethostbyname($this->host)){
            throw new Exception(‘Error resolving host IP
address.’);
        }
        return $ip;
    }
    // get list of IP addresses
    public function getIpList(){
        if(!$ips=implode(‘ – ‘,gethostbynamel($this->host))){
            throw new Exception(‘Error getting list of IP
addresses for the provided hostname.’);
        }
        return $ips;
    }
    // get host name
    public function getHost(){
        if(!$host=gethostbyaddr($this->getIp())){
            throw new Exception(‘Error resolving host name.’);
        }
        return $host;
    }
    // get TCP ports of Internet services
    public function getServicePorts(){
        $output=’Retrieving services ports…Please wait.<br />';
        foreach($this->services as $service){
            if(!$port=getservbyname($service,’tcp’)){
                $output.=’Error retrieving port of service
‘.$service.'<br />';
            }
            else{
                $output.=’Service ‘.$service. ‘ runs on TCP
port :’. $port.'<br />';
            }
        }
        return $output;
    }
    // get Services by TCP ports
    public function getServiceNames(){
        $output=’Retrieving services names…Please wait.<br />';
        foreach($this->ports as $port){
            if(!$service=getservbyport($port,’tcp’)){
                $output.=’Error retrieving service name on port
‘.$port.'<br />';
            }
            else{
                $output.=’TCP Port ‘.$port. ‘ is used by
service :’. $service.'<br />';
            }
        }
        return $output;
    }
}

As you can see, the “QueryProcessor” class has a few handy methods, which use some of the most common PHP networking functions. With regards to this, the class is capable of resolving a specific host name to its corresponding IP address(or eventually a list of IP addresses), as well as performing the inverse process, that is given an IP address, turning it to the respective Internet host.

In addition, the query processor exposes two extra methods. The first one is focused on retrieving the number of the TCP port that corresponds to a specific service, while the second one performs the inverse process, obtaining the name of a service provided at a given TCP port.

Having covered at a glance how the “QueryProcessor” class was originally defined, here is an example that shows how to use its methods:

try{
    // instantiate ‘QueryProcessor’ object
    $queryProc=new QueryProcessor(‘hotmail.com’);
    // display host IP address
    //echo $queryProc->getIp(); // displays 64.4.32.7
    // display host name
    //echo $queryProc->getHost(); // displays ‘hotmail.com.br’
    // display IP list
    //echo $queryProc->getIpList(); // displays 64.4.32.7 -
64.4.33.7
    // display services ports
    echo $queryProc->getServicePorts();
    /* displays the following list
    Retrieving services ports…Please wait.
    Service http runs on TCP port :80
    Service https runs on TCP port :443
    Service ftp runs on TCP port :21
    Service telnet runs on TCP port :23
    Service imap runs on TCP port :143
    Service smtp runs on TCP port :25
    Service nicname runs on TCP port :43
    Service gopher runs on TCP port :70
    Service finger runs on TCP port :79
    Service pop3 runs on TCP port :110
    Service www runs on TCP port :80
    */
    // display service names
    echo $queryProc->getServiceNames();
    /* displays the following list
    Retrieving services names…Please wait.
    TCP Port 21 is used by service :ftp
    TCP Port 23 is used by service :telnet
    TCP Port 25 is used by service :smtp
    TCP Port 43 is used by service :nicname
    TCP Port 70 is used by service :gopher
    TCP Port 79 is used by service :finger
    TCP Port 80 is used by service :http
    TCP Port 110 is used by service :pop3
    TCP Port 143 is used by service :imap
    TCP Port 443 is used by service :https
    */
}
catch(Exception $e){
    echo $e->getMessage();
    exit();

As shown in the above example, once an Internet host name has been passed to the class constructor, the subsequent calls to the respective methods demonstrate how to obtain the corresponding IP address for that host, or the full list of IP addresses. They also display the TCP ports associated with specific services and, inversely, show the service that runs on a given port.

As you can see, most of these class methods are very simple, but you can see how they can be used as the building blocks of larger networking PHP applications.

Now, it’s time to continue expanding the existing functionality of the “QueryProcessor” class, so please click on the link below in order to learn how you can implement the popular “ping” and “ipconfing” Windows utilities as new class methods.

{mospagebreak title=Adding more functionality to the “QueryProcessor” class: defining the “Ping()” and “IpConfig()” methods}

The first method that I will add to the class is “IpConfig(),” which, as the name clearly suggests, is responsible for executing the “ipconfig” Windows-based utility. In case you didn’t know, this program will let you know the network settings of your Windows system, including the IP address, subnet mask, DNS suffixes, default gateway, and so on for each of the network adapters installed on your computer.

Having described the functionality of the “ipconfig” Windows utility, take a look at the method below, which runs this command on a Windows machine:

// execute ‘ipconfig’ command on Windows systems
public function IpConfig(){
    $output=’Running ipconfig command…Please wait.<br />';
    exec(‘ipconfig’,$lines);
    foreach($lines as $line){
        $output.=$line.'<br />';
    }
    return $output;
}

In this case, the above “Ipconfig()” method uses the “exec()” PHP built-in function, in order to perform the homonymous Windows utility. As you know, this function allows the execution of commands on the server (provided that you have the right permissions) and returns the corresponding results as an array structure.

After executing the “ipconfig” command, the output is returned to calling code, simply by iterating over the output array returned by the “exec()” function. Evidently, this method is really simple to read and code, thus I’ll move on to the next one, “Ping(),” which runs the popular “ping” command on Windows-based systems. Please take a look at the way this method is defined:

// execute ‘ping’ command on Windows systems
public function Ping(){
    $output=’Running ping command…Please wait.<br />';
    exec(‘ping ‘.$this->host,$lines);
    foreach($lines as $line){
        $output.=$line.'<br />';
    }
    return $output;
}

As illustrated in the above code block, the “Ping()” method looks nearly identical to the previous one. Of course, the only difference rests on the type of Window command executed, which in this case is the famous “ping” utility. Similar to the “IpConfig()” method that you learned before, this method first uses the “exec()” PHP function, in order to run the “ping” program, and next returns the result as an array.

Due to the numerous similarities exposed by the two methods, it’s possible to merge them into one and avoid writing additional code. However, I want you to learn each method as a separate block of code, since it’s much simpler to read and understand.

Now, after defining the prior methods, I’ll code two new methods in the next section, which also use the “exec()” PHP native function for doing its business on Windows systems. To learn more on this please keep on reading.

{mospagebreak title=More methods ahead: defining the “Netstat()” and “getMXRecordsWin()” methods}

As you’ve seen in the previous section, running commands on Windows-based systems can be quite useful for executing some well-know utilities. That’s exactly the case with the “netstat” command, which can be used basically for checking the status of your different network connections. That said, here is the class method that runs that command on a Windows-based computer:

// execute ‘netstat’ command on Windows systems
public function Netstat(){
    $output=’Running netstat command…Please wait.<br />';
    exec(‘netstat’,$lines);
    foreach($lines as $line){
        $output.=$line.'<br />';
    }
    return $output;
}

As you can appreciate, this new method also uses the PHP “exec()” function, in order to execute the “netstat” command. As with the previous cases, after running this command, the output is processed as an array, which is traversed by a regular “foreach” loop, and finally returned to calling code.

Since the above method is very easy to grasp, I won’t spend a long time explaining its logic. I’ll move forward and show you the last method (at least for this article) that uses the PHP “exec()” function for running Windows commands. What I referencing here is the “getMXRecordsWin()” method, which comes in handy for getting the list of MX records that correspond to a given Internet host. The source code of this method is listed below:

// get MX records on Windows systems
public function getMXRecordsWin(){
    $output=’Retrieving MX Records…please wait.<br />';
    exec(“nslookup -type=mx $this->host”,$mxhosts);
    foreach($mxhosts as $mxhost){
        $output.=$mxhost.'<br />';
    }
    return $output;
}

In this case, the method shown above utilizes the “exec()” function for running the “nslookup” utility in conjunction with the “type” flag, in order to obtain (when applicable) the list of MX records corresponding to an Internet host. As you’ll recall, this host is passed to the constructor and assigned as a class property, thus obtaining the respective MX records for it is really a no-brainer process.

All right, at this stage I added some valuable networking methods to the “QueryProcessor” class, in order to expand its existing capabilities. Therefore, it’s convenient that you see how the class looks now, after attaching the new methods. To see the full source of the class, please jump into the next section.

{mospagebreak title=Gluing the pieces together: listing the full source code of the “QueryProcessor” class}

Undoubtedly, you’ll have a better idea of how the new methods fit into the structure of the “QueryProcessor” class if you see its full source code, so here is the complete definition of this class:

class QueryProcessor{
    private $host;
    private $services=array
(‘http’,’https’,’ftp’,’telnet’,’imap’,’smtp’,’nicname’,
‘gopher’,’finger’,’pop3′,’www’);
    private $ports=array(21,23,25,43,70,79,80,110,143,443);
    public function __construct($host=’myhost.com’){
        $this->host=$host;
    }
    // get IP address
    public function getIp(){
        if(!$ip=gethostbyname($this->host)){
            throw new Exception(‘Error resolving host IP
address.’);
        }
        return $ip;
    }
    // get list of IP addresses
    public function getIpList(){
        if(!$ips=implode(‘ – ‘,gethostbynamel($this->host))){
            throw new Exception(‘Error getting list of IP
addresses for the provided hostname.’);
        }
        return $ips;
    }
    // get host name
    public function getHost(){
        if(!$host=gethostbyaddr($this->getIp())){
            throw new Exception(‘Error resolving host name.’);
        }
        return $host;
    }
    // get TCP ports of Internet services
    public function getServicePorts(){
        $output=’Retrieving services ports…Please wait.<br />';
        foreach($this->services as $service){
            if(!$port=getservbyname($service,’tcp’)){
                $output.=’Error retrieving port of service
‘.$service.'<br />';
            }
            else{
                $output.=’Service ‘.$service. ‘ runs on TCP
port :’. $port.'<br />';
            }
        }
        return $output;
    }
    // get Services by TCP ports
    public function getServiceNames(){
        $output=’Retrieving services names…Please wait.<br />';
        foreach($this->ports as $port){
            if(!$service=getservbyport($port,’tcp’)){
                $output.=’Error retrieving service name on port
‘.$port.'<br />';
            }
            else{
                $output.=’TCP Port ‘.$port. ‘ is used by
service :’. $service.'<br />';
            }
        }
        return $output;
    }
    // execute ‘ipconfig’ command on Windows systems
    public function IpConfig(){
        $output=’Running ipconfig command…Please wait.<br />';
        exec(‘ipconfig’,$lines);
        foreach($lines as $line){
            $output.=$line.'<br />';
        }
        return $output;
    }
    // execute ‘ping’ command on Windows systems
    public function Ping(){
        $output=’Running ping command…Please wait.<br />';
        exec(‘ping ‘.$this->host,$lines);
        foreach($lines as $line){
            $output.=$line.'<br />';
        }
        return $output;
    }
    // execute ‘netstat’ command on Windows systems
    public function Netstat(){
        $output=’Running netstat command…Please wait.<br />';
        exec(‘netstat’,$lines);
        foreach($lines as $line){
            $output.=$line.'<br />';
        }
        return $output;
    }
    // get MX records on Windows systems
    public function getMXRecordsWin(){
        $output=’Retrieving MX Records…please wait.<br />';
        exec(“nslookup -type=mx $this->host”,$mxhosts);
        foreach($mxhosts as $mxhost){
            $output.=$mxhost.'<br />';
        }
        return $output;
    }
}

Now that you’ve seen the complete source code of the “QueryProcessor” class, below I coded an example that demonstrates how to use some of these new methods:

// instantiate ‘QueryProcessor’ object
$queryProc=new QueryProcessor(‘google.com’);
// display MX records
echo $queryProc->getMXRecordsWin();
/* displays the following output:

Retrieving MX Records…please wait.
Server: dns0c.dnserver.com.ar
Address: 200.51.212.7

google.com MX preference = 10, mail exchanger = smtp1.google.com
google.com MX preference = 10, mail exchanger = smtp2.google.com
google.com MX preference = 10, mail exchanger = smtp3.google.com
google.com MX preference = 10, mail exchanger = smtp4.google.com

google.com nameserver = ns3.google.com
google.com nameserver = ns4.google.com
google.com nameserver = ns1.google.com
google.com nameserver = ns2.google.com
smtp1.google.com internet address = 216.239.57.25
smtp2.google.com internet address = 64.233.167.25
smtp3.google.com internet address = 64.233.183.25
smtp4.google.com internet address = 66.102.9.25
ns1.google.com internet address = 216.239.32.10
ns2.google.com internet address = 216.239.34.10
ns3.google.com internet address = 216.239.36.10
ns4.google.com internet address = 216.239.38.10

*/

// display ‘netstat’ results
echo $queryProc->NetStat();
/* displays the following output:

Running netstat command…Please wait.

 Active Connections

Proto local address remote address  status
TCP mywebserver:http localhost:3677 ESTABLISHED
TCP mywebserver:3677 localhost:http ESTABLISHED

*/

// display ‘ping’ results
echo $queryProc->Ping();
/* displays the following output:
pinging google.com [72.14.207.99] with 32 bytes of data:

Response from 72.14.207.99: bytes=32 time=247ms TTL=237
Response from 72.14.207.99: bytes=32 time=234ms TTL=237
Response from 72.14.207.99: bytes=32 time=234ms TTL=237
Response from 72.14.207.99: bytes=32 time=234ms TTL=238

Ping statistics for 72.14.207.99:
Packets: sent = 4, received = 4, lost = 0
(0% lost),
Approximated response time en milliseconds:
Min = 234ms, Max = 247ms, Average = 237ms

*/

To wrap up

Over this second article in the series, you learned how to run popular Windows network monitoring utilities, such the “ping”, “netstat” and “ipconfig” programs, by adding some new methods to the “QueryProcessor” class. Additionally, you saw how to retrieve the list of MX records corresponding to a given Internet host, by using the “exec()” PHP function, which comes in handy for running system commands.

Nevertheless, my introduction to PHP programming has not finished yet. In the last tutorial, I’ll be defining a few additional methods for the “QueryProcessor” class that can be useful for scanning TCP ports, finding DNS records and much more. Just don’t miss it!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan