HomePHP Page 4 - Completing a Query Processor in PHP
Scanning TCP ports, running a WHOIS service and more: defining the scanPort() and getWhois() methods - PHP
Welcome to the third part of the series “Network Programming in PHP.” In three tutorials, this series explains the basics of network programming in PHP, by developing a query processor class in PHP 5, which uses some of the most popular PHP network functions, in order to implement the logic of its methods.
The last two methods of the "QueryProcessor" class tackle different tasks. The first one, "scanPort()," not surprisingly checks whether a given TCP port is available for connections, and its source code is the following:
// scan TCP ports public function scanPort($port=80){ if(!is_int($port)||$port<1||$port>65535){ throw new Exception('Invalid TCP port number.'); } $output='Scanning port '.$port.'...please wait.<br />'; if(!$fp=@fsockopen($this->host,$port,$errno,$errstr,30)){ throw new Exception('Unable to open connection to port '.$port); } fclose($fp); return 'Port '.$port.' is open to connections.'; }
As shown above, the "scanPort()" method verifies whether or not a specific TCP port is open to connections by using the powerful "fsockopen()" PHP function. In this case, if the port in question isn't available, a new exception is thrown. Otherwise, a string is returned, confirming that the connection has been successfully established.
Now that you know how the "scanPort()" method works, turn your attention to the last method of the class, called "getWhois()," which implements a basic "WHOIS" service. Please take a look at its source code:
// get basic WHOIS info public function getWhoIs(){ $output='Retrieving WHOIS information...please wait.<br />'; if(!$fp=fsockopen("whois.opensrs.net",43,$errno, $errstr,30)){ throw new Exception('Error opening socket connection to WHOIS server.'); } sleep(2); fputs($fp,"$this->hostrn"); while(!feof($fp)){ $output.=fread($fp,128).'<br />'; } fclose($fp); return $output; }
Surely, you'll agree with me the above method is really easy to understand. What it does essentially is implement a basic WHOIS service, by opening a socket connection to the "whois.opensrc.net" WHOIS host. Of course, this is merely an example of how to build this kind of service, and should be used with caution and responsibility. Eventually, you may want to change the WHOIS server and use another one.
Similar to the previous methods that you learned, if the connection to the host is successfully established, the server response is returned to calling code, while if the connection fails, an exception is thrown. Simple, right?
At this stage, I think all the methods I coded earlier complete the "QueryProcessor" class. Now, it's time to see the full source code for this class, after adding the additional methods I wrote before. Want to see the complete definition for the query processor? Go ahead and read the next few lines.