in reply to Socket connection to random IP, with fallback

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!

Replies are listed 'Best First'.
Re^2: Socket connection to random IP, with fallback
by kwaping (Priest) on May 17, 2006 at 15:31 UTC
    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.