# #!/usr/bin/perl use Socket; #use strict; use FileHandle; my $note; my @storage; my $flag; my @message; &Server; sub Server { use Socket; use Carp; my ($port, $proto, $paddr, $iaddr, $name); sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n"; } $port = shift || 4000; socket(Server, PF_INET, SOCK_STREAM, $proto) or die "socket: $!"; setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) or die "setsockopt: $!"; bind(Server, sockaddr_in($port, INADDR_ANY)) or die "bind: $!"; listen(Server, SOMAXCONN) or die "listen: $!"; logmsg "server started on port $port, type ^c to terminate"; for( ; $paddr = accept(Client, Server); close(Client)) #handshake1,2 { ($port, $iaddr) = sockaddr_in($paddr);#handshake3 $name = gethostbyaddr($iaddr, AF_INET); logmsg "connection from $name [", inet_ntoa($iaddr), "] at port $port"; @storage=(); my $hdr; my $last; autoflush Client; $last = "\r\n"; $note = "\r\n"; while ($note=) { if($note != "\n" && $last != "\n") {break;} $last=$note; $hdr .= $note; } print "Whole shebang: " . $hdr; my @requests = split /\s/, $note; $note=@requests[0]; print "newcmd: " . $note . "\n"; print "newfile: " . @requests[1] . "\n"; if($note eq 'GET') { if (@requests[1] eq '/') #if whole directory is requested { $dir="/Users/micahaci/www/"; opendir DH, $dir; foreach $file (readdir DH) { if ($file =~ /^\./){} #no files that start with . else { open PAGE, $dir.$file or die "couln't open " . $file;; print "1File: " . $file . "\n"; while() { print Client $_; } close PAGE; push(@storage,$file); } } } else #if a specific file is requested { open PAGE, $dir . @requests[1]; print "2File: " . @requests[1] . "\n"; if (PAGE==undef) {print Client "HTTP/1.0: 404 Page not found\r\n";} while() { print Client $_; } close PAGE; push(@storage,$file); } shutdown(Client,2); } } }