tags:

views:

51

answers:

2

I am using IO::Socket::INET to create inter-process communication in my program. I need to use a specific port number in my TCP client. I was following the example in Perl doc, but it doesn't work. Here is my code:

old code(working):

tx_socket = new IO::Socket::INET->new('127.0.0.1:8001') || die "Can't connect to 127.0.0.1:8001 : $!\n"; 

new code(not working):

tx_socket = new IO::Socket::INET->new('127.0.0.1:8001', LocalPort=>9000 ) || die "Can't connect to 127.0.0.1:8001 : $!\n"; 

Does anyone know what's wrong?

+1  A: 

According to the documentation, you should be doing something like:

$sock = IO::Socket::INET->new(
    PeerAddr  => '127.0.0.1',
    PeerPort  => 8001,
    LocalPort => 9000,
    Proto     => 'tcp'
) or die "Connect error: $!";
Grant McLean
I tried this format also, the INET function call does not return a valid socket. I called $sock->print after the code, Perl complains about $sock is an undefined value.
alex
If the new method returns undef then you should look for an error message in $!. I've added the error check above.
Grant McLean
A: 

Grant McLean's answer works, if you fix the missing comma, but "works" here may be relative to what you are expecting.

use IO::Socket::INET;
$sock = IO::Socket::INET->new(
    PeerAddr  => '127.0.0.1',
    PeerPort  => 8001,
    LocalPort => 9000,
    Proto     => 'tcp'
);
die("No socket!\n") unless $sock;
print "Socket good!\n";

Running this yields:

No socket!

Which isn't because the code doesn't work, it's working as expected (in my case). That is, it's expected that a connection to a localhost port 8001 will fail with nothing listening on the other side. This illustrates the usefulness of error reporting:

use IO::Socket::INET;
$sock = IO::Socket::INET->new(
    PeerAddr  => '127.0.0.1',
    PeerPort  => 8001,
    LocalPort => 9000,
    Proto     => 'tcp'
) or die("$!\n");
die("No socket!\n") unless $sock;
print "Socket good!\n";

Which running now yields:

Connection refused

If I run netcat listening on port 8001, I get a different result:

Socket good!
kbenson
Thanks kbenson and Grant, it is working now by using the code you posted.
alex