[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] Echo server on 7 IPs in < 40 lines of code



Project: You're trying to test some load balancing architecture. You need a program that will listen to port 443 on 7 different IPs simultaneously. It should accept multiple simultaneous TCP connections. For each connection it should echo the fist line of input back to the client and then disconnect (like the world's stupidest web server).

Note: IO::Multiplex rules.

Solution:
-----------
use IO::Socket;
use IO::Multiplex;

my $mux  = new IO::Multiplex;

for (153..159) {
   # Create a listening socket
   my $sock = new IO::Socket::INET(
      Proto     => 'tcp',
      LocalPort => 443,
      LocalAddr => "10.0.37.$_",
      Listen    => 4
   ) or die "socket: $@";

   # We use the listen method instead of the add method.
   $mux->listen($sock);
}

$mux->set_callback_object(__PACKAGE__);
$mux->loop;

sub mux_input {
   my $package = shift;
   my $mux     = shift;
   my $fh      = shift;
   my $input   = shift;

   $fh->send("$$input\n");
   $$input = undef;
   $mux->shutdown($fh, 1);
   $mux->shutdown($fh, 0);
   $mux->shutdown($fh, 2);
   $mux->kill_output($fh);
   $mux->close($fh);
}
-----------

Run it (as root) and poof!:

# lsof -n -i:443
COMMAND   PID USER   FD   TYPE DEVICE SIZE NODE NAME
perl 11508 root 3u IPv4 29046 TCP 10.0.37.153:https (LISTEN) perl 11508 root 4u IPv4 29047 TCP 10.0.37.154:https (LISTEN) perl 11508 root 5u IPv4 29048 TCP 10.0.37.155:https (LISTEN) perl 11508 root 6u IPv4 29049 TCP 10.0.37.156:https (LISTEN) perl 11508 root 7u IPv4 29050 TCP 10.0.37.157:https (LISTEN) perl 11508 root 8u IPv4 29051 TCP 10.0.37.158:https (LISTEN) perl 11508 root 9u IPv4 29052 TCP 10.0.37.159:https (LISTEN)

Mwoo haha ahah aha,

j