nikhilx64 has asked for the wisdom of the Perl Monks concerning the following question:

I have two PERL programs that I am attempting to connect via sockets. The code below works fine when I attempt to connect to the socket on the same machine i.e. localhost.

Program: socketopen

use warnings; use IO::Socket; my $sock = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => '12345', Proto => 'tcp', Listen => 1, ReuseAddr => 1, ); die "Could not create socket : $!\n" unless $sock; print "Socket created: $sock\n"; my $newsock = $sock->accept(); while (<$newsock>) { print $_; } close($sock);

Program: socketconnect

use warnings; use IO::Socket; my $sock = new IO::Socket::INET ( PeerAddr => '192.168.x.xx', PeerPort => '12345', Proto => 'tcp', ); die "Could not create socket : $!\n" unless $sock; print $sock "Hello there!\n"; close($sock);
As soon as move one program to another machine I get: "Could not create socket : Connection refused"

Both machines are running Ubuntu. I know that the port is in a listening state from the output of netstat -tlp. And the Ubuntu firewall is inactive on both machines.

Any help and nudges in the right direction will be greatly appreciated.

Replies are listed 'Best First'.
Re: Socket connection refused problem
by ikegami (Patriarch) on Feb 01, 2011 at 07:04 UTC
    Get rid of «LocalHost => 'localhost'». Your specifically only allow connection from the loopback adapter. If you don't specify LocalHost, connections will be accepted from any interface.
Re: Socket connection refused problem
by andal (Hermit) on Feb 01, 2011 at 08:38 UTC

    If you do "ping localhost" you'll see which IP address is really used. Normally it is 127.0.0.1 which is the address that is used only within the same machine. Using this address you can't connect from one machine to another. For this each machine must have another IP address, and if everything is setup correctly, then the name associated with that address is reported by command 'hostname'.

    So, just make sure that both scripts use the same IP address, and that IP address is not the "local" one.

Re: Socket connection refused problem
by nikhilx64 (Initiate) on Feb 01, 2011 at 15:21 UTC
    Thanks guys!

    I removed the LocalAddress => 'localhost' parameter while creating the socket and it works!

    I also tried LocalAddress => 'xx.xx.xx.xx' (the actual machine IP address) and that works too!

    I knew that localhost corresponds to the local loop-back address. But I thought LocalAddress was a necessary parameter for the socket constructor and it never struck me to use the machine IP directly. I did try using the machine hostname, but that didn't work either.

    Thanks again guys, I trawled the web looking for a solution but couldn't find any. I can continue with my socket programs now that that this has been solved.