a socket example in perl

B

bad_knee

This is an example for all the folks new to perl that are
looking for a way to connect to a server and retrieve some
data.

This program will connect to a newserver, download the list
of newsgroups, and then print it to the screen.

Note: You may not want to do this on a dialup connection.

cheers,
bl8n8r

###############################################################################
#!/usr/bin/perl -w

use strict;
use IO::Socket;

#
# server to contact must be first arg from command line
# eg: getnews news.creativelabs.com
#
my $NewsServer = $ARGV[0];


# make sure an argument was given
if (length ($NewsServer) < 1)
{
die ("arg0 == server to connect to. quitting");
}


# the main subroutine returns the list of newsgroups
sub Main()
{
my $buf = "";
my $sock = new IO::Socket::INET (PeerAddr => $NewsServer, PeerPort
=> '119', Proto => 'tcp') || die "$!\n";
my $data = "";
my $bytes = 0;

# connect to news server
print "connecting to $NewsServer\n";

# send list command
$sock->send("list\r\n");

# read list
while (1)
{
# read a chunk of data
$data = "";
$sock->recv ($data, 1024, 0);
$bytes = length ($data);

# append data to buffer
$buf = $buf.$data;

# read until "dot" all by itelf as in RFC0977
# we search for \r\n.\r\n cuz the buffer itself
# may end with a dot in the middle of the listing
if ($data =~ m/\x0d\x0a.\x0d\x0a$/)
{
last;
}

}

# send quit command to server
$sock->send("quit\r\n");

# close socket to server
close($sock);

return ($buf);
}


# print buffer results
print "".Main();
 
T

Tony Curtis

On 13 Apr 2004 14:27:15 -0700,
This is an example for all the folks new to perl that are
looking for a way to connect to a server and retrieve some
data.
This program will connect to a newserver, download the list
of newsgroups, and then print it to the screen.

Net::NNTP would be a lot easier.

hth
t
 
S

Sherm Pendley

bad_knee said:
This is an example for all the folks new to perl that are
looking for a way to connect to a server and retrieve some
data.

Nice of you to post an example of using raw sockets, but it's also worth
mentioning that quite often, the protocol you want to use is already
wrapped up in a nice, simple CPAN module.
This program will connect to a newserver, download the list
of newsgroups, and then print it to the screen.

So will this one:

#!/usr/bin/perl

use strict;
use warnings;

use
my $c = new print $c->list;

sherm--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,147
Messages
2,570,835
Members
47,382
Latest member
MichaleStr

Latest Threads

Top