#!/usr/bin/perl # # ICS 243d - Internet Technology # Spring Quarter 2001 # Roberto Silveira Silva Filho ID# 85849631 # Fake Web Server # Assignment 2 # # based on file: tcp_echo_serv1.pl # form the Book: Network Programming with Perl by Lincoln D. Stein # ---------------------------------------------------------- # usage: tcp_echo_serv1.pl [port] use strict; use Socket; use IO::Handle; use constant MY_WEB_PORT => 16004; my ($bytes_out,$bytes_in) = (0,0); my $port = shift || MY_WEB_PORT; my $protocol = getprotobyname('tcp'); # Prints the home page that introduces the server and launches the client example. print "Connection: close\n"; print "Content-type: text/html\n\n"; print ""; print "web server - cgi Perl test"; print "\n"; print "

Fake Web Server STARTED


"; print "
The server is running on port $port
"; print "

Test Here: http://rodan.ics.uci.edu:$ port/\n\n"; print "


\n\n"; # Subroutine declaration $SIG{'INT'} = sub { print STDERR "bytes_sent = $bytes_out, bytes_received = $bytes_in\n"; exit 0; }; socket(SOCK, AF_INET, SOCK_STREAM, $protocol) or die "socket() failed: $!"; setsockopt(SOCK,SOL_SOCKET,SO_REUSEADDR,1) or die "Can't set SO_REUSADDR: $!" ; my $my_addr = sockaddr_in($port,INADDR_ANY); bind(SOCK,$my_addr) or die "bind() failed: $!"; listen(SOCK,SOMAXCONN) or die "listen() failed: $!"; warn "waiting for incoming connections on port $port...\n"; next unless my $remote_addr = accept(SESSION,SOCK); my ($remotePort,$hisaddr) = sockaddr_in($remote_addr); warn "Connection from [",inet_ntoa($hisaddr),",$remotePort]\n"; SESSION->autoflush(1); # Generates a page whenever the server is accesse by a web server. # It dies after the generation. while () { # print SESSION "Content-type: text/html\n\n"; print SESSION ""; print SESSION " Fake Web server page "; print SESSION "\n"; print SESSION "

Fake Web Server



"; print SESSION " This is a HTML page generated on port $port
"; print SESSION " The browser used port $remotePort to request this page

"; print SESSION ""; warn "Connection from [",inet_ntoa($hisaddr),",$port] finished\n"; warn "Closing session...\n"; close SESSION; } close SOCK;