#!/usr/bin/perl use Socket; use Carp; use FileHandle; # (1) use port 80 by default, unless overridden on command line $port = 80; # (2) create local TCP socket and set it to listen for connections socket(S,PF_INET,SOCK_STREAM,getprotobyname('tcp')) || die ("ERROR:Connection Creation Failed\n"); setsockopt(S, SOL_SOCKET, SO_REUSEADDR, 1) || die ("ERROR: setsockopt() Failed\n"); bind(S, sockaddr_in($port, INADDR_ANY)) || die ("ERROR: bind() Failed\n"); listen(S, SOCKMAXCONN) || die ("ERROR: listen() Failed\n"); # (3) print a startup message printf(" <<>>\n\n",$port); while (1) { # (4) wait for a connection C $cport_caddr = accept(C, S); ($cport,$caddr) = sockaddr_in($cport_caddr); C->autoflush(1); # (5) print who the connection is from $cname = gethostbyaddr($caddr,AF_INET); print "Host: $cname\n"; # (6) read request msg until blank line, and print on screen $temp = ; ($method, $request, $http) = split(" ",$temp); # check whether it's / in which case make it index.html if($request eq "/"){ $request = "/index.html"; } # remove .. to filter directory traversal attacks $request =~ s/\.\.//; #check file exists if ( -e "./htdocs/$request" ){ print "200 - $cname $request\n"; $page=""; open FILE, "<./htdocs/$request"; while(){ $page .= $_; } close(FILE); print C "HTTP/1.0 200 OK\r\n"; print C "Content-type: text/html\r\n"; print C "\r\n"; print C "$page"; }else{ print "404 - $cname $request\n"; print C "HTTP/1.0 404\r\n"; print C "Content-type: text/html\r\n"; print C "\r\n"; print C "404 Page Not Found"; print C "404 - $request not found"; } close(C); }