On 3/8/07, mlist <[EMAIL PROTECTED]> wrote:
I have a script which will create a socket connection to a host. It
should loop through while the socket connection is active. The problem
is that it still continues to loop even if I take down the interface on
the host machine. What am I missing (no doubt somthing simple). Any
help would be appreciated.
#!/usr/bin/perl
use warnings;
use strict;
use IO::Socket;
my $counter = 1;
my $whileloop = 0;
my $sock = new IO::Socket::INET (
PeerAddr => '10.5.7.33',
PeerPort => '21',
Proto => 'tcp',
);
die "Could not create socket: $!\n" unless $sock;
while ($whileloop < 1) {
if ($sock) {
printf "Socket connected\n";
printf "$counter\n";
$counter++;
sleep 2;
} else {
my $whileloop = 99;
}
}
close($sock);
printf "Socket closed\n";
I don't understand why you are using the $whileloop variable. Perl
has perfectly good loop control mechanisms. A quick rewrite would be
while (1) {
if ($sock) {
printf "Socket connected\n";
printf "$counter\n";
$counter++;
sleep 2;
} else {
last;
}
}
But why have two conditions in the first place? Also, why are you
using printf? You aren't doing any formating. For that matter why do
you have two print statements when you only need one.
#!/usr/bin/perl
use warnings;
use strict;
use IO::Socket;
my $counter = 1;
#don't use "new class", use "class->new"
my $sock = IO::Socket::INET->new(
PeerAddr => '10.5.7.33',
PeerPort => '21',
Proto => 'tcp',
) or die "Could not create socket: $!\n";
while ($sock->connected) {
print "Socket connected\n$counter\n";
$counter++;
sleep 2;
}
$sock->close;
print "Socket closed\n";
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/