Reputation: 9026
Here is a sample that fails:
#!/usr/bin/perl -w
# client.pl
#----------------
use strict;
use Socket;
# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 55555;
my $server = "10.126.142.22";
# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
or die "Can't create a socket $!\n";
connect( SOCKET, pack( 'Sn4x8', AF_INET, $port, $server ))
or die "Can't connect to port $port! \n";
my $line;
while ($line = <SOCKET>) {
print "$line\n";
}
close SOCKET or die "close: $!";
with the error:
Argument "10.126.142.22" isn't numeric in pack at D:\send.pl line 16.
Can't connect to port 55555!
I am using this version of Perl:
This is perl, v5.10.1 built for MSWin32-x86-multi-thread
(with 2 registered patches, see perl -V for more detail)
Copyright 1987-2009, Larry Wall
Binary build 1006 [291086] provided by ActiveState http://www.ActiveState.com
Built Aug 24 2009 13:48:26
Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl". If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.
While I am running the netcat command on the server side. Telnet does work.
Upvotes: 2
Views: 1314
Reputation: 1
This is the line that make the packing work:
connect( SOCKET, pack( 'SnC4x8', AF_INET, $port, split /\./,$server ))
or die "Can't connect to port $port! \n";
Upvotes: 0
Reputation: 97918
Works like this for me:
connect( SOCKET, pack( 'S n a4 x8', AF_INET, $port, $server))
or die "Can't connect to port $port! \n";
I think your original script AF_INET
is unicode or something. If you delete the A
and write again it works.
Upvotes: 1
Reputation: 239672
The problem is that the pack template Sn4x8
is in error — and shouldn't be used in the first place. Something like pack_sockaddr_in($port, inet_aton($server))
as documented in Socket would be more likely to work.
But ideally, you wouldn't use the low-level Socket code at all. Here's a nicer bit of code that does it using IO::Socket, which is also a core part of perl for the past 15 years:
use strict;
use IO::Socket::INET;
my $host = shift || 'localhost'; # What is this here for? It's not used
my $port = shift || 55555;
my $server = "10.126.142.22";
my $socket = IO::Socket::INET->new(
PeerAddr => $server,
PeerPort => $port,
Proto => 'tcp',
) or die "Can't connect to $server: $@";
while (my $line = <$socket>) {
print $line; # No need to add \n, it will already have one
}
close $socket or die "Close: $!";
Upvotes: 7