Sockets aren't all about HTTP

While receiving compressed content is not a particularly amazing thing to do with fsockopen(), it should at least demonstrate the fact that it gives you a lot more control over your sockets than simply using fopen(). For example, if we wanted to do something other than read HTTP, we just need to change the port number - here is a script that reads in Whois information about a site:

<?php
    $fp = fsockopen ("whois.networksolutions.com", 43);

    if ($fp) {
        fwrite($fp, "microsoft.com\n");

        while (!feof($fp)) {
            print fread($fp,256);
        }

        fclose ($fp);
    } else {
        print"Fatal error\n";
    }
?>

It looks similar to the last one, as I am sure you can see. The difference is that this time we connect to the Whois database of Network Solutions, which contains registrar information for .com, .net, and .org domains, and we query it for information on microsoft.com. Port 43 is the "whois" port, used for these kind of queries, which means that the Network Solutions server is listening for clients who connect on port 43. As soon as we connect, we provide a domain name followed by a line return, which is part of the very basic Whois protocol - doing this signals to the Whois server that we want it to return Whois information on the server we specified.

Give that script a try, although it is only for trial purposes alone - as you will see in the output, Network Solutions request that you don't use their Whois database as part of "high-volume, automated, electronic processes". Please remember that the Internet relies on a lot of co-operation between people, so respect their wishes!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Sockets can be servers >>

Previous chapter: Making a simple search engine

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.