in reply to compare server response?

While your socket is staying open the data is being buffered so not being flushed back to your client, so it won't see the response until the socket is closed (which won't happen unless you're telling it to (e.g. by sending a QUIT command that it understands) or the server hangs up on you)

In this example a web connection sends a "Connection: close" which gets the server to hangup - thus flushing the output.

#!/usr/bin/perl use strict; use warnings; use IO::Socket; my $server = "remote.server.net"; my $port = 43; my $path = "/"; my $socket=IO::Socket::INET->new( PeerAddr => $server, PeerPort => $port, Proto=> 'tcp') || die "Can't connect to $server:$port: $!\n"; my $data = qq~GET $path HTTP/1.1 Host: $server Accept: */* User-Agent: My Perl Script Pragma: no-cache Cache-Control: no-cache Connection: close ~; print $socket "$data\r\n"; my $body = 0; while(<$socket>) { my $line = $_; if ($body eq 1) { print $line; } $body = 1 if ($line=~/Connection: close/i); } close($socket);
If you were connecting to an FTP server for example you would send "QUIT\n"

If you're reading the data in a while loop and then sending something which is hanging up the connection when you see what you want:

#!/usr/bin/perl use strict; use warnings; use IO::Socket; my $remote_server = "ftp.server.net"; my $remote_port = 21; my $sock = IO::Socket::INET->new("$remote_server:$remote_port") || die + $!; my $data = "HELP"; my $string_to_compare = "^220 "; print $sock "$data\r\n"; my @output; $| = 1; while (<$sock>) { push(@output, $_); print $sock "QUIT\n" if /$string_to_compare/gi; } close($sock); my $output = join('', @output); sub true { print "Ain't dat da true! :o)\n"; # open(tmpl, "email.txt") || print $!; } sub false { print "Close, but no banana.\n"; } if ($output =~ /$string_to_compare/gi) { &true; } else { &false; }
it can sometimes make a difference if you put:
$| = 1;
Just before the while loop, which turns off buffering - thus auto-flushing the response from the server (see perlvar and look for $OUTPUT_AUTOFLUSH ) - but in your example the line
my @output = <$sock>;
is just going to sit there forever waiting for an EOF and the program will never get to the
$output = join('', @output);
to carry on with the rest of the logic.

Replies are listed 'Best First'.
Re^2: compare server response?
by webshark (Acolyte) on Dec 07, 2005 at 17:37 UTC
    Thanks serf... this looks exactly what I need... minus the banana of course ;-)