alex
alex

Reputation: 275

How can I specify which port to use in Perl's IO::Socket::INET?

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?

Upvotes: 0

Views: 1863

Answers (2)

Grant McLean
Grant McLean

Reputation: 6998

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: $!";

Upvotes: 1

kbenson
kbenson

Reputation: 1464

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!

Upvotes: 1

Related Questions