Some Computer Hints


Perl Script - Web “Browser”

If you want to browse some page from an http server on the Internet from command line, this very simple script may help you. This Perl script will connect to the server you specified using the port you give and will request and display a page.

#!/usr/bin/perl
# wb.pl - Simple web "browser".
# Fedon Kadifeli, 1997 - April 2003.

$usage='wb.pl [server [port [URL]]]';
$date='08/04/2003 15:50';
$version='0.03';

die "Usage: $usage\n" if $#ARGV>2;

( $server, $port, $url ) = @ARGV;

$port = 80 unless $port;
$server = 'localhost' unless $server;
$url = '/' unless $url;

$AF_INET = 2;
$SOCK_STREAM = 1;

$SIG{'INT'} = 'dokill';

sub dokill {
  kill 9,$child if $child;
}

$sockaddr = 'S n a4 x8';

($name,$aliases,$proto) = getprotobyname('tcp');
($name,$aliases,$port) = getservbyname($port,'tcp')
    unless $port =~ /^\d+$/;

($name,$aliases,undef,undef,$thataddr) = gethostbyname($server);
die "$server: $!\n" unless defined $thataddr;

$this = pack($sockaddr, $AF_INET, 0, "");
$that = pack($sockaddr, $AF_INET, $port, $thataddr);

@ip = unpack("C4", $thataddr);
print STDERR "Server: @ip - Port : $port - URL : $url\n";

socket(S, $AF_INET, $SOCK_STREAM, $proto) or die "socket: $!\n";
bind(S, $this)   or die "bind: $!\n";
connect(S,$that) or die "connect: $!\n";

select(S); $| = 1; select(STDOUT);

print S "GET $url HTTP/1.0\n\n";
while( <S> ) {
  print;
}
close (S);

The script takes three parameters. You can use it like this:

perl wb.pl example.com 80 http://example.com/
perl wb.pl www.boun.edu.tr

In the first example we had to use the full URL in the third parameter since example.com is a virtual host. In the second example, the implied third parameter / was enough. Please note that you cannot access https sites with this script.