Home arrow PHP arrow Page 2 - Build a Query Processor Class for Networking in PHP 5

Building the class: Converting host names to IP addresses and vice versa - PHP

Welcome to the first of three tutorials in a series that covers network programming in PHP. In this article you will learn how to use some useful PHP networking functions that will help you perform a variety of common networking tasks. To that end, you will build a simple networking query application in PHP 5.

TABLE OF CONTENTS:
  1. Build a Query Processor Class for Networking in PHP 5
  2. Building the class: Converting host names to IP addresses and vice versa
  3. Handling Internet services: defining the "getServiceNames()" and "getServicePorts()" methods
  4. Assembling the methods: listing the full source code of the "QueryProcessor" class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 8
May 17, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

A good place to start coding the PHP 5 class that implements my networking query application is naturally with defining its constructor method, which takes up just one incoming parameter for doing its business: the name of the Internet host being queried.

Since this is merely my first attempt at coding the class, for the moment this host name will be passed, for instance, in the form "hostname.com" or "hostname.net" or whatever you want to pass as host name to the class, without checking whether or not the host exists.

Keeping in mind the initial condition that I mentioned above, the skeleton of the PHP 5 class, which not surprisingly I named "QueryProcessor," can be defined as follows:

class QueryProcessor{
    private $host;
    public function __construct($host='myhost.com'){
        $this->host=$host;
    }
}

As shown by the above snippet of code, the "QueryProcessor" class has only one method (this is only temporary), that is its constructor, which accepts as a unique parameter the name of the Internet host being queried. In this case I also decided to assign a default value for the corresponding host name (myhost.com), but obviously you should change this value and provide another host name.

Right, now that you saw how the primitive structure of the above class looks, it's time to provide the class with the ability to do something more useful than assigning the respective host name as a class property. For this reason, what I'll do next is add a couple of methods to the class, which come in handy for converting the specified host name to its corresponding IP address, and eventually for getting the complete list of IP addresses that match the given host name.

Here are the signatures for these two new methods:

// get IP address
public function getIp(){
    if(!$ip=gethostbyname($this->host)){
        throw new Exception('Error converting hostname to 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;
}

As shown above, these two new methods, that is "getIp()" and "getIpList()" respectively, can be used to convert the specified host name to its IP address. In case you want to go one step further, they can also be used to obtain the entire set of IP addresses that correspond to that host.

With regard to the first method, I used the "gethostbyname()" PHP built-in function, which gets the IP address corresponding to the specified Internet host name. If the IP address can't be obtained for some reason, this function will return the same string that was passed as host name.

Now, if you turn your attention to the second method, you'll see that I used another useful PHP function, "gethostbynamel()," in order to obtain the entire list of IP addresses that match the given host. Since this function returns the respective IP addresses as an array, I made the "getIpList()" method return a string containing all the IP addresses, separated by a "-" character. Just in case the host name can't be resolved to a list of IP addresses, the method will throw an exception.

At this point, I provided the class with the capacity to turn a given host name into a single IP address, or eventually a list of them. Thus, this conversion process wouldn't be complete if I don't include an opposite method, that is one that converts an IP address to an Internet host name.

For the sake of completeness, below I listed the "getHost()" method, which is responsible for reversing the process and getting the IP address that corresponds to a specified Internet host name:

// get host name
public function getHost(){
    if(!$host=gethostbyaddr($this->getIp())){
        throw new Exception('Error resolving host name.');
    }
    return $host;
}

As illustrated above, the "getHost()" method uses the "gethostbyaddr()" PHP built-in function, in order to obtain the IP address corresponding to a given Internet host. Also, notice that I internally utilized the public "getIp()" method for getting the IP address in question and then passing it to the function.

However, it seems that the above method is really redundant, because the respective host name has already been passed in as an argument to the constructor. Well, the reason for including this method rests mainly in the functionality of the class, since you may want to modify its code and redefine this method, in order to take up any well-formed IP address and convert it to its host name.

Additionally, there's another interesting thing that you can experiment with when using this method: if you're passing to it the same IP address, over and over again, and you get different host names at times, these results may be a consequence of dealing with a host that shares multiple domains.

At this point, I defined three methods that convert a specific host name to its corresponding IP addresses and vice versa. So now, take a look at the definition of the improved "QueryProcessor" class:

class QueryProcessor{
    private $host;
    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;
    }
}

Okay, at this stage the "QueryProcessor" class is now capable of performing some useful tasks, which implies using a few networking PHP functions. Nevertheless, there's a long way ahead of us, so it's time to jump into the next section and continue adding more methods to the class.

Want to learn how this will be done? Please click on the link below and keep reading.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: