Skip to Main Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced content levelIntermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

IO::Socket

use IO::Socket;

As a client:

$socket = new IO::Socket::INET (PeerAddr => $remote_host,
                                PeerPort => $remote_port,
                                Proto    => "tcp",
                                Type     => SOCK_STREAM)
    or die "Can't connect to $remote_host:$remote_port : $!\n";# Or use the simpler single-argument interface.
$socket = IO::Socket::INET->new("$remote_host:$remote_port");
                              # "localhost:80", for example.
print $socket "data\n";
$line = <$socket>;

As a server:

$server = IO::Socket::INET->new(LocalPort => $server_port,
                                Type      => SOCK_STREAM,
                                Reuse     => 1,
                                Listen    => 10 )  # or SOMAXCONN
    or die "Can't be a TCP server on port $server_port : $!\n";while ($client = $server->accept()) {
    # $client is the new connection
    $request = <$client>;
    print $client "answer\n";
    close $client;
}
# Make simple TCP connecting function that returns a filehandle
# for use in simple client programs.
sub tcp_connect {
    my ($host, $service) = @_;
    require IO::Socket;
    return  IO::Socket::INET->new(join ":", $host, $service);
}
my $fh    = tcp_connect("localhost", "smtp");  # with scalar
local *FH = tcp_connect("localhost", "smtp");  # with handle

The IO::Socket module provides a higher-level approach to socket handling than the raw Socket module. You may use it in an object-oriented fashion, although this isn't mandatory, because the return values are proper filehandles and may be used as such, as shown in the tcp_connect function in the example. This module inherits methods from IO::Handle, and itself requires IO::Socket::INET and IO::Socket::UNIX. See the description of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata