#!/usr/bin/perl use IO::Socket; @ARGV == 1 || die "usage: $0 port\n"; if ($ARGV[0] < 1 || $ARGV[0] > 65535) { die "$ARGV[0] is not a valid port\n"; } my ($port) = @ARGV; open(FILE,"fortunes"); while ($fortune = ) { chomp($fortune); push @fortunes,$fortune; $db_size++; } close(FILE); if (!$db_size) { die "fortunes file is empty\n"; } my $server = IO::Socket::INET->new( Listen => SOMAXCONN, LocalPort => $port, Reuse => 1, Proto => 'tcp' ) || die "can't open server socket connection: $!"; while (defined($remote = $server->accept)) { # accept multiple clients $remote->autoflush(1); $hostinfo = gethostbyaddr($remote->peeraddr, AF_INET); print STDERR "[Received connection from ", $hostinfo || $remote->peerhost," on $port]\n"; while (<$remote>) # listen on command channel { if (/GET/i) { srand; # seed the random number function $num = int (rand $db_size); # get a random fortune $length = length($fortunes[$num]); if ($length < 10 || $length > 99) { $fortune = "Your fortune was not of valid length."; } print $remote "$length\n"; print $remote "$fortunes[$num]\n"; } elsif (/BYE/i) { close($remote); } } }