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

I've borrowed the code below from the Perl cookbook (Chap 17).

Started with TCP sockets (see links), but really want Unix domain (##URL REMOVED##) (as the clients/server will be on the same machine).

The INET version works fine, but converting the socket to Unix as shown means no input seems to arrive at the server.

Server (##URL REMOVED##)

use POSIX; use IO::Socket; use IO::Select; use Socket; use Fcntl; use Tie::RefHash; + $port = N; # change this at will + # Listen to port. #$server = IO::Socket::INET->new(LocalPort => $port, # Listen => 10 ) # or die "Can't make server socket: $@\n"; + unlink "/tmp/mysock"; $server = IO::Socket::UNIX->new(Local => "/tmp/mysock", Type => SOCK_STREAM, Listen => 5 ) or die "Failed to make socket: $!";
Client (##URL REMOVED##)
use IO::Socket; + #$socket = IO::Socket::INET->new(PeerAddr => "x.x.x.x", # PeerPort => "N", # Proto => "tcp", # Type => SOCK_STREAM) # or die "Couldn't connect to x.x.x.x :N : $@\n"; + $socket = IO::Socket::UNIX->new(PeerAddr => "/tmp/mysock", Type => SOCK_STREAM, Timeout => 10 ) or die $@;
Obviously I've obscured the actual machine ip/port.

Edited by Chady -- removed link to copyrighted material

Replies are listed 'Best First'.
Re: Unix domain sockets problem
by thospel (Hermit) on Oct 18, 2004 at 11:27 UTC
    In the server code you forget to do an accept, so after setting up the listening socket you simply exit and nothing is listening anymore. Add $server->accept and it will wait for one connection.

    In the client code you use PeerAddr instead of Peer.

    Fix these two and it will work.

    And I don't think you should worry terribly about bugs in IO::Socket::UNIX. It gets tested as part of the perl selftest after build.

      Actually, the code in the Cookbook for the server does include accept, I just didn't want to clutter up the page with lots of code.

      Anyway, changing to Peer on the client fixed it. I'm surprised it didn't throw an error on the original. This means the book is wrong as it's a straight copy of the code there.

      BTW, any idea which would be faster ie local INET vs UNIX?

Re: Unix domain sockets problem (IP++)
by tye (Sage) on Oct 18, 2004 at 05:44 UTC

    Use IP sockets and bind to localhost. You'll have fewer problems, as IP sockets get constant exercise that keeps the bugs off.

    - tye