8.2. Socket level programming using Socket.pmExample 8-1. examples/network/socket.pl #!/usr/bin/perl
use strict;
use warnings;
use Socket qw(:DEFAULT :crlf);
# Using the built in "socket" function with various helper variables
# and functions from the standard Socket.pm module
# get the protocol id (on Linux from /etc/protocols)
my $protocol_id = getprotobyname('tcp');
# build C structure in_addr from hostip
# if hostname is given it tries to resolve hostname to ip first (and returns
# undef if not successful)
#my $host = '127.0.0.1';
my $host = 'localhost';
#my $host = '66.249.85.99';
#my $host = 'www.google.com';
my $host_struct = inet_aton($host);
# inet_ntoa($host_struct) returns the resolved ip address
my $port = 80;
socket(my $socket, PF_INET, SOCK_STREAM, $protocol_id) or die $!;
my $sockaddr_in = pack_sockaddr_in($port, $host_struct);
connect($socket, $sockaddr_in) or die $!;
# turn off buffering on the socket
{
my $old = select($socket);
$| = 1;
select($old);
}
print $socket "GET /$CRLF";
while (my $line = <$socket>) {
print $line;
}
|
Follow me: