Hi,
I had to make a proxy server for a CS class. It uses perl and IO::Sockets. Here is my code. Hopefully it will be useful since it is implements both server and client code (the nature of a proxy server). If you are doing this for a class assignment yourself, please only use the code for reference. Otherwise have fun with it. I'm not that good of a perl programmer so all of the experts I'm sure will find flaws with it :-)
#!/usr/bin/perl -w
#################################
# Jaz Server Proxy
#################################
# Joe Jaisnski
# Networking
# Due: Oct 5 2004
#################################
$|=1; # flush buffer
use strict; # enable strict mode to require var declara
+tion
use IO::Socket; # use the IO::Sockets library
my $server_port = 7788; # define the port that the proxy will run o
+n
my ($server); # declare the server variable
# establish the server socket
my $socket_server = IO::Socket::INET->new( Listen => 5, LocalPort => $
+server_port,
Reuse => 1, Proto => 'tcp'
+)
or die "cannot connect to port $server_port: $!";
while ($server = $socket_server->accept()) # loop while the file hand
+le is true (infinate loop)
{
my ($response_all, $content_length) = ("", 1000); # declare some
+vars
my (@request_headers, @response_all); # declare some
+vars
local $/ = "\015\012"; # set the loop
+break string
while (<$server>) # while the soc
+ket is being accessed
{
chomp; # remove the newl
+ine at the end of each line
last if $_ eq ''; # break loop if i
+nput is empty
push(@request_headers, $_ . "\n"); # push the input
+onto an array
}
my ($host, $port) = $request_headers[1] =~ m/^Host:\s*([\w\d\.\-]+
+):?(\d*)/mi; # parse host and port
my ($path) = $request_headers[0] =~ m#^GET (.+) HTTP/1.[01]# ;
+ # parse out path
# replace micorsoft.com with sourceforge.com if the host contains
+MS or is empty
if (($host =~ "microsoft.com") or ($host eq "")) { $host = "www.so
+urceforge.net"; $path = "/";}
if (!defined($port) or ($port eq '')) { $port = "80"; } # ch
+eck to see if port is defined
$request_headers[0] = "GET $path HTTP/1.1\n"; # se
+tup replacement GET header
$request_headers[1] = "Host: $host:$port\n"; # se
+tup replacement Host: header
# establish the client socket with newly determined host
my $socket_client = IO::Socket::INET->new( PeerAddr => $host,
PeerPort => $port, Prot
+o => 'tcp')
or die "cannot connect to port $port at $host: $!";
print $socket_client join('', @request_headers) . "\n"; # pr
+int headers to the socket
my $client; # define scalar
while($client = <$socket_client>) # read in retrieved content fr
+om the client socket
{ print $server $client; } # print the content to the bro
+wser
$socket_client->close; # close the connection
$server->close; # close the connection
($host, $port, $path) = (undef, undef, undef); # undefine the ho
+st port and path vars
}
|