user1201988
user1201988

Reputation: 21

Perl - creating a Socket

i'm trying to create a socket that connects to a website and send GET request but when i do that i got an error.

here is my code

#!/usr/bin/perl -w 
use IO::Socket;
$socket = IO::Socket::INET->new(
PeerAddr => "www.googel.com",
PeerPort => "http(80)",
Proto => "tcp");
die "Error: $!";
print $socket "GET / HTTP/1.0";
close $socket;

and the error is :

Error: Illegal seek at socket.pl line 7.

Upvotes: 0

Views: 3583

Answers (3)

Pegasus Epsilon
Pegasus Epsilon

Reputation: 124

I can't believe this question is as old as it is and still has no technically correct answer.

The problem is that you're telling your program to die, no matter what. At the end of IO::Socket::INET->new() you have a semicolon, terminating that statement. The next statement is die "Error: $?"; which will ALWAYS die. $? just happens to be set to "Illegal seek" -- You haven't created this error, and neither has anything else in your program, it's just what $? happens to be set to at the moment.

Nothing is causing an error except that you've replaced "or" with ";" after the IO::Select::INET->new() (or before die, depending on your perspective). Remove the semicolon, add the "or", change "googel.com" to "google.com", and add a double carriage-return/newline at the end of the request per https://www.rfc-editor.org/rfc/rfc1945 (ie: print $socket "GET / HTTP/1.0\r\n\r\n";) and the program will function as you expect.

Upvotes: 1

kbenson
kbenson

Reputation: 1464

Here's another version with a slight fix for line endings, and receiving a single line of input and displaying it.

#!/usr/bin/env perl
use strict;
use warnings;
use IO::Socket;

my $socket = IO::Socket::INET->new(
    PeerAddr => 'www.google.com',
    PeerPort => 'http(80)',
    Proto    => 'tcp',
) or die("Error :: $!");

print($socket "GET / HTTP/1.1\r\n");
print($socket "\r\n");
my $recv_line = <$socket>;
print $recv_line;

Although if you are planning to actually access a URL or scrape content, I highly advise you use LWP::UserAgent or one of the many alternatives.

Upvotes: 1

Toto
Toto

Reputation: 91518

Use this instead:

#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;

my $socket = IO::Socket::INET->new(
    PeerAddr => "www.googel.com",
    PeerPort => "http(80)",
    Proto => "tcp") or  # Note or instead of ;
#                 __^__
       die "Error: $!";
print $socket "GET / HTTP/1.0";
close $socket;

Upvotes: 2

Related Questions