http://www.perlmonks.org?node_id=1018649

cspctec has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to write a script that will connect to the telnet port on my device, send a command, and get the reply back. My script is currently not returning the result of the command I send.
#!/usr/bin/perl use strict; use warnings; use IO::Socket; my ($host, $port) = ('111.111.111.111', '23'); my $command = "\$TEMP*"; my $socket = new IO::Socket::INET ( PeerAddr => $host, PeerPort => $port, Proto => 'tcp', ); if (!$socket) { die "Unable to establish connection to $host\n"; } print $socket $command; $socket->getline; my $output = <$socket>; $socket->close; print "$output\n";

So the script is suppose to open a socket on port 23, send the command $TEMP* and then get the result that the device will give. The script either hangs or it just returns the "Welcome to device 'devicename', please input your commands".

Is there anyway to make the script wait and grab the output after the command $TEMP* is input? The device is suppose to return something like $TEMP*,42C.

Replies are listed 'Best First'.
Re: Getting a response from a socket
by 7stud (Deacon) on Feb 13, 2013 at 23:50 UTC

    Both of these lines:

    $socket->getline; my $output = <$socket>;

    ...read 'line oriented' input, i.e. they return when they read a newline from the socket. So if you want to read all the lines from the socket, you can use one of these:

    while ( defined( my $line = $socket->getline ) ) { } while (my $line = <$socket>) { } my @lines = <$socket>;

    The script either hangs or it just returns the "Welcome to device 'devicename', please input your commands".

    Well, then it sounds like you should start your program by reading a line at a time from the socket--until the line you read matches that text, then send your command. Then read some more lines for the response.
Re: Getting a response from a socket
by NetWallah (Canon) on Feb 14, 2013 at 03:42 UTC
    If you are using IO::Socket older than version 1.18, you may need to manually turn on autoflush.

                 Most people believe that if it ain't broke, don't fix it.
            Engineers believe that if it ain't broke, it doesn't have enough features yet.

Re: Getting a response from a socket
by VinsWorldcom (Prior) on Feb 14, 2013 at 00:25 UTC
      Thank you for the suggestions everyone, I will try those. Also, the reason I'm not using Net::Telnet is because the unix boxes I'm working on here are usually outdated and there is absolutely nothing I can do to update them. They do not have Net::Telnet installed (I REALLY wish they did!).