Wednesday, April 16, 2008

perl: simple socket programming

Here's a telnet kinda program in perl (i.e. a generic TCP client):

#!/usr/bin/perl
use IO::Socket;

my $dest = shift;
my $port = shift;
my $message;
my $line;

my $sock = IO::Socket::INET -> new ( PeerAddr => $dest, PeerPort => $port, Proto => "tcp" ) or die "Could not establish TCP connection: $!";

$sock->autoflush(1);

while (1)
{
    $message = <stdin>;
    print $sock $message;

    while ($line = <$sock>)
    {
        print $line;
    }
}

close $sock;

No comments: