I think this code might be useful as a very low-tech load balancer, or in an n-tier environment.

The code starts by randomly selecting an IP from an array, then tries to make a socket connection to it. If that fails, it will try again until every IP in the array has been used. If the socket successfully connects, it stops trying.
use IO::Socket; my @ips = ('XXX.XXX.XXX.X0','XXX.XXX.XXX.X1','XXX.XXX.XXX.X2'); my $port = XXXX; # grab an IP randomly my $index = int(rand(scalar @ips)); my $sock; for (my $counter = 0; $counter < scalar @ips; $counter++) { # try to connect $sock = IO::Socket::INET->new( PeerAddr => $ips[$index].':'.$port, Blocking => 1, Timeout => 1, ); # success! last if ($sock); # failure - get previous IP (loops around if negative, pretty sweet) $index--; }

Replies are listed 'Best First'.
Re: Socket connection to random IP, with fallback
by ruzam (Curate) on May 16, 2006 at 22:34 UTC
    If say, you had 50 ips in the array, and a block of 40 of them where duds, then you wouldn't get a very load balanced selection from the remaining 10. The burden would largely keep falling on a single ip and you'd probably be just as well off looping through the array sans random?

    Instead of looping around the array, I would remove each try from the remaining pool:
    use IO::Socket; my @ips = ('XXX.XXX.XXX.X0','XXX.XXX.XXX.X1','XXX.XXX.XXX.X2'); my $port = XXXX; my $sock; while (@ips) { # radmomly pick an ip from the list (removing it at the same time) my $ip = splice(@ips, rand(@ips), 1); # try to connect $sock = IO::Socket::INET->new( PeerAddr => $ip.':'.$port, Blocking => 1, Timeout => 1, ); # success! last if ($sock); }
    I did like your negative index trick!
      Very nice modification, thank you! My environment only has a couple servers, so I hadn't considered the situation you described. I'm probably going to adapt your splice method into my code. I've adapted your splice method into my production code. I left the snippet unmodified though, just to show another method.

      ---
      It's all fine and dandy until someone has to look at the code.