0

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
alex
  • 275
  • 1
  • 7
  • 16
  • 1
    Why are you calling `new` twice on the same object? see http://stackoverflow.com/questions/429657/what-is-the-difference-between-new-someclass-and-someclass-new-in-perl – Ether Apr 29 '10 at 02:14

2 Answers2

1

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
  • 6,898
  • 1
  • 21
  • 37
  • 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 Apr 29 '10 at 01:53
  • If the new method returns undef then you should look for an error message in $!. I've added the error check above. – Grant McLean Apr 29 '10 at 11:10
1

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
  • 1,464
  • 9
  • 13