Sunday, September 6, 2009

Perl Socket Example

The aim of this tutorial is to show how to read and write a socket in Perl. We will open a socket to a website, write the request headers, read the response and write the response to the console. You do not need any prior HTTP 1.x knowledge.

First lets have a look at the example. It's really self explanatory.
 1.     use IO::Socket;
 3.     my $sock = new IO::Socket::INET (PeerAddr => 'localhost',
 4.                                         PeerPort => 8080, 
 5.                                         Proto => 'tcp');
 6.     die "could not create socket: $!\n" unless $sock;                                        
 8.     printf $sock ("GET / HTTP/1.0\n");
 9.     printf $sock ("Host: localhost\n");
10.     printf $sock ("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
11.     printf $sock ("User-Agent: Mozilla/5\n");
12.     printf $sock ("Connection: keepalive\n");
13.     printf $sock ("\n\n");
15.     while (<$sock>) {
16.         if($_=~ m/validate_response/i) {
17.              last;
18.         }
19.          else{
20.              print $_;
21.         }
22.     }
Hide line numbers

Line 3 We open the socket to localhost on port 8080. This is where my server tomcat ususally runs. But you can change this to anything

Lines 8-13 Here we write out the reust HEADER to the webserver. Just remember if you change your host from 'localhost' to something else, you need to change line 9 to reflect that too.

Lines 15-22 Read the response from the webserver and write it to the screen.

No comments: