Question

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?

Was it helpful?

Solution

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!

OTHER TIPS

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: $!";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top