Networking Clients
Use Internet-domain sockets when you want reliable client-server communication between potentially different machines.
To create a TCP client that connects to a server somewhere, it’s
usually easiest to use the standard IO::Socket::INET module:
#!/usr/bin/env perl
use v5.14;
use warnings;
use autodie;
use IO::Socket::INET;
my $remote_host = "localhost"; # replace with real remote host
my $remote_port = "daytime"; # replace with service name or portnumber
my $socket = IO::Socket::INET–>new(
PeerAddr => $remote_host,
PeerPort => $remote_port,
Type => SOCK_STREAM,
);
# send something over the socket; netstuff likes CRLFs
# daytime doesn't take input, but use on other servers
print $socket "Why don't you call me anymore?\r\n";
# read the remote answer,
my $answer = <$socket> =~ s/\R\z//r;
say "Got answer: $answer";
# and terminate the connection when we're done.
close($socket);A shorthand form of the call is good enough when you just have a host and port combination to connect to, and are willing to use defaults for all other fields:
$socket = IO::Socket::INET–>new("www.yahoo.com:80")
or die "Couldn't connect to port 80 of yahoo: $!";For IPv6, it’s easiest if you get the IO::Socket::IP module from CPAN. If you have a release of Perl later
than v5.14, it may even be on our system already. Once you’ve done that,
all you do is change the name of the class in the code above from
IO::Socket::INET to IO::Socket::IP, and
it will work for IPv6, too. That class is an extra
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.
Read now
Unlock full access