use strict; use warnings; require IO::Handle; # let's us use sockets as objects. require IO::Socket::IP; # Implicitly included above, yet list it explicitly: require Socket; # When no arg1 is passed, the socket buffer section is skipped. # Otherwise, this is the value to set as the SO_RCVBUF on the socket. my $buf_size = shift; # Notably, we cannot use IO::Socket::IP or related classes. # Setting socket options (like SO_RCVBUF we do later) requires we do them on # an otherwise *unconnected* socket. We handle this ourselves here: my $host = "google.com"; my $port = 80; socket(my $sock, Socket->AF_INET, Socket->SOCK_STREAM, Socket->IPPROTO_TCP); defined $sock or die "no socket: $!"; # Set socket buffer, when requested: my $size; if ($buf_size) { my $rc; # Show current buf: $size = getsockopt($sock, Socket->SOL_SOCKET, Socket->SO_RCVBUF); die "No buf size??" unless defined $size; printf "Size of buffer before setting is: %s\n", unpack("i", $size); # Set new size: $rc = setsockopt($sock, Socket->SOL_SOCKET, Socket->SO_RCVBUF, pack("i", $buf_size)); die "setsockopt() failed" unless ($rc); } # Regardless, show the current size: $size = getsockopt($sock, Socket->SOL_SOCKET, Socket->SO_RCVBUF); die "No buf size after set??" unless defined $size; printf "Size of buffer is now: %s\n", unpack("i", $size); print "Sleeping 2..\n"; sleep 2; my $hints = { family => Socket->AF_INET, protocol => Socket->IPPROTO_TCP, }; my ($err, @addrs) = Socket::getaddrinfo( $host, $port, $hints ); die "getaddrinfo error: $err ($!)" if ($err); my $ai = shift @addrs or die "no addresses for the host!"; connect($sock, $ai->{addr}) or die "Connect failed: $!"; $sock->autoflush(1); # Use Perl/IO (built on Standard I/O) to send a request for data: $sock->print("GET /\n") or die "Socket error on write: $!"; # Read loop, printing out data from socket to STDOUT. my $rc; while (1) { $rc = $sock->read(my $buffer, 1024); # catch socket errors (excluding EOF): unless (defined $rc) { die "Socket error on read: $!"; } # EOF returns 0, which exits the read loop: last if ($rc == 0); # Otherwise print the line, which may be a partial line. #printf "%s\n", $buffer; } print "\n";