start page | rating of books | rating of authors | reviews | copyrights

Book HomeJava and XSLTSearch this book

15.2. The IO::Socket Module

The IO::Socket module included in the core Perl distribution provides an object-oriented approach to socket programming. This module provides a convenient way to handle the large number of options you have to deal with, and it handles the laborious task of forming addresses. IO::Socket is built upon the Socket module provided in the standard library. It inherits from IO::Handle, which supports a class of filehandle objects for much of the IO library. The following IO::Socket functions are simply frontends for the corresponding built-in functions and use the same syntax:

socket
socketpair
bind
listen
send
recv
peername (same as getpeername)
sockname (same as getsockname)

The accept function in IO::Socket is slightly different from the equivalent function, however, and is described later in the chapter.

IO:Socket contains two subclasses: INET and UNIX. The INET subclass is used to create and manipulate Internet-domain sockets, such as those used in the examples. The UNIX subclass creates Unix domain sockets.

15.2.1. Client-Side Sockets

IO::Socket greatly simplifies the implementation of a socket for client communications. The following example creates an Internet-domain socket (using the INET subclass) and attempts to connect to the specified server:

use IO::Socket;
$sock = new IO::Socket::INET (PeerAddr => 'www.ora.com',
                              PeerPort => 80,
                              Proto    => 'tcp');
die "$!" unless $sock;

IO::Socket::INET::new creates an object containing a socket filehandle and connects it to the host and port specified in PeerAddr and PeerPort. The object $sock can then be written to and read from like other socket filehandles.

15.2.2. Server-Side Sockets

On the server side, IO::Socket provides a nice wrapper for creating server sockets. The wrapper encompasses the socket, bind, and listen procedures, while creating a new IO::Socket object. For example, we can create an Internet-domain socket with IO::Socket::INET:

use IO::Socket;
$sock = new IO::Socket::INET (LocalAddr => 'maude.ora.com',
                              LocalPort => 8888,
                              Proto     => 'tcp',
                              Listen    => 5);
die "$!" unless $sock;

The parameters for the new socket object determine whether it is a server or a client socket. Because we're creating a server socket, LocalAddr and LocalPort provide the address and port to bind to the socket. The Listen parameter gives the queue size for the number of client requests that can wait for an accept at any one time.

When the server receives a client request, it calls the accept method on the socket object. This creates a new socket object on which the rest of the communication can take place:

$new_sock = $sock->accept( );

When communication is finished on both client and server sockets, they should be destroyed with close. If a socket is not properly closed, the next time you attempt to use a socket with the same name, the system will complain that the socket is already in use.

15.2.3. IO::Socket Methods

The following methods are defined in IO::Socket and can be used on socket objects of either the INET or UNIX class.

accept

accept ([pkg])

Performs the accept system call on a socket and returns a new object. The new object is created in the same class as the listen socket, unless pkg is specified. The object can be used to communicate with the client that tried to connect. In a scalar context, the new socket is returned, or undef is returned on failure. In an array context, a two-element array is returned containing the new socket and the peer address, or an empty list is returned on failure.

protocol

protocol

Returns the protocol number for the protocol being used on the socket, if known. If the protocol is unknown, as with an AF_UNIX socket, returns 0

sockdomain

sockdomain

Returns the number representing the socket address domain. For example, an AF_INET socket has the value &AF_INET.

sockopt

sockopt (opt, [val])

Sets and retrieves socket option opt in the SOL_SOCKET level. The value val is set for the option, if given. If no value is provided, the function returns the current setting for the option.

socktype

socktype

Returns the number representing the socket type. For example, a SOCK_STREAM socket has the value &SOCK_STREAM.

timeout

timeout ([val])

Sets or retrieves the timeout value associated with a socket. Without an argument, the current value is returned. If a timeout of val is given, the setting is changed to val, and the previous value is returned.

15.2.4. IO::Socket::INET Reference

An Internet-domain socket is created with the new method from the IO::Socket::INET subclass. The constructor can take the following options:

PeerAddr => hostname[:port]
Specifies the remote host and optional port number for a client connection. hostname can be either a name, such as www.oreilly.com, or an IP number of the form 207.44.21.2.

PeerPort => port
Specifies the port number on the remote host for a client connection. The name of the service (such as http or nntp) may be used for the argument if the port number is not known.

LocalAddr => hostname[:port]
Specifies the local address (and optional port number) to bind to a server-side socket.

LocalPort => port
Specifies the local port number (or service name) to bind to a server-side socket.

Proto => name
Specifies the protocol to be run on the socket, i.e., tcp or udp.

Type => SOCK_STREAM | SOCK_DGRAM
Specifies the type of socket. SOCK_STREAM indicates a stream-based socket connection, and SOCK_DGRAM indicates a message-based (datagram) connection.

Listen => n
Sets the listen-queue size to n number of client requests.

Reuse => 1
Given a nonzero number, this option allows the local bind address to be reused should the socket need to be reopened after an error.

Timeout => n
Sets the timeout.

Whether a server (receiving) or client (requesting) socket is created depends on the parameters provided to the constructor. If Listen is defined, a server socket is automatically created. If no protocol is specified, it is derived from the service on the given port number. If no port number is given, tcp is used by default.

15.2.4.1. IO::Socket::INET methods

The following methods can be used on socket filehandle objects created by IO::Socket::INET.

15.2.5. IO::Socket::UNIX Reference

The IO::Socket::UNIX subclass creates a Unix-domain socket. Unix-domain sockets are local to the current host and are used internally to implement pipes, thus providing communication between unrelated processes. Using sockets provides finer control than using named pipes, also called FIFO (first-in, first-out) buffers. This is because receiving sockets can distinguish between different client connections, which can then be assigned to different sessions with the accept call.

The IO::Socket::UNIX constructor (new( )) creates the socket and returns an object containing a filehandle. The constructor can take the following options:

Type => SOCK_STREAM | SOCK_DGRAM
Indicates the type of socket: SOCK_STREAM for streaming, SOCK_DGRAM for packets or datagrams.

Local => pathname
Provides the pathname of the FIFO buffer to bind to the socket.

Peer => pathname
Provides the pathname to the destination FIFO buffer.

Listen => n
Creates a listen socket and sets the queue size to n.

The following methods can be used on an object created with IO::Socket::UNIX.

hostpath

hostpath

Returns the pathname to the local FIFO buffer.

peerpath

peerpath

Returns the pathname to the destination or peer FIFO.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.