Help-Site Computer Manuals
Software
Hardware
Programming
Networking
  Algorithms & Data Structures   Programming Languages   Revision Control
  Protocols
  Cameras   Computers   Displays   Keyboards & Mice   Motherboards   Networking   Printers & Scanners   Storage
  Windows   Linux & Unix   Mac

Socket::Class
A class to communicate with sockets

Socket::Class - A class to communicate with sockets


NAME

Socket::Class - A class to communicate with sockets


SYNOPSIS


  use Socket::Class;


DESCRIPTION

Socket::Class provides a simple, fast and efficient way to communicate with sockets. It operates outside of the PerlIO layer and can be used as a replacement of IO::Socket. Little parts of Bluetooth technology has been integrated. Please see below.

Bluetooth

The standard build includes Bluetooth protocols for RFCOMM (stream) and L2CAP (datagram). Bluetooth adapters on a MS-Windows operation system must be compatible with the Windows Bluetooth API to get it working. More specific Bluetooth support could be added in the future.

Functions by Category

Main Functions

accept, bind, close, connect, free, new, listen, reconnect, shutdown

Sending and Receiving

print, printf, read, readline, recv, recvfrom, say, send, sendto, write, writeline

Address Functions

get_hostaddr, get_hostname, local_addr, local_path, local_port, pack_addr, remote_addr, remote_path, remote_port, unpack_addr

Socket Options

get_blocking, get_broadcast, get_option, get_rcvbuf_size, get_reuseaddr, get_sndbuf_size, get_timeout, get_tcp_nodelay, set_blocking, set_broadcast, set_option, set_rcvbuf_size, set_reuseaddr, set_sndbuf_size, set_timeout, set_tcp_nodelay

Miscellaneous Functions

fileno, handle, is_readable, is_writable, select, sleep state, to_string, wait

Error Handling

errno, error, is_error


EXAMPLES

Simple Internet Server


  use Socket::Class qw($SOMAXCONN);

  

  # create a new socket at port 9999 and listen for clients 

  $server = Socket::Class->new(

       'local_port' => 9999,

       'listen' => $SOMAXCONN,

  ) or die Socket::Class->error;

  

  # wait for clients

  while( $client = $server->accept() ) {

      # somebody connected to us (we are local, client's address is remote)

      print 'Incoming connection from '

          . $client->remote_addr . ' port ' . $client->remote_port . "\n";

      # do something with the client

      $client->say( 'hello client' );

      ...

      $client->wait( 100 );

      # close the client connection and free its resources

      $client->free();

  }

Simple Internet Client


  use Socket::Class;

  

  # create a new socket and connect to the server at localhost on port 9999

  $client = Socket::Class->new(

       'remote_addr' => 'localhost',

       'remote_port' => 9999,

  ) or die Socket::Class->error;

  

  # do something with the socket

  $str = $client->readline();  

  print $str, "\n";

  

  # close the client connection and free its resources

  $client->free();

Simple HTTP Client


  use Socket::Class;

  

  # create a new socket and connect to www.perl.org

  $sock = Socket::Class->new(

       'remote_addr' => 'www.perl.org',

       'remote_port' => 'http',

  ) or die Socket::Class->error;

  

  # request the main site

  $sock->write(

      "GET / HTTP/1.0\r\n" .

      "User-Agent: Not Mozilla\r\n" .

      "Host: " . $sock->remote_addr . "\r\n" .

      "Connection: Close\r\n" .

      "\r\n"

  ) or die $sock->error;

  

  # read the response (1MB max)

  $sock->read( $buf, 1048576 )

      or die $sock->error;

  

  # do something with the response

  print $buf;

  

  # close the socket an free its resources

  $sock->free();

Bluetooth RFCOMM Client


  use Socket::Class;

  

  # create a new socket and connect to a bluetooth device 

  $sock = Socket::Class->new(

      'domain' => 'bluetooth',

      'type' => 'stream',

      'proto' => 'rfcomm',

      'remote_addr' => '00:16:20:66:F2:6C',

      'remote_port' => 1, # channel

  ) or die Socket::Class->error;

  

  # do something with the socket

  $sock->send( "bluetooth works" );

  

  ...

  

  # close the connection and free its resources

  $sock->free();


METHODS

Constructing

new ( [%arg] )
Creates a Socket::Class object, which is a reference to a newly created socket handle. new() optionally takes arguments, these arguments are in key-value pairs.

  remote_addr    Remote host address             <hostname> | <hostaddr>

  remote_port    Remote port or service          <service> | <number>

  remote_path    Remote path for unix sockets    "/tmp/mysql.sock"

  local_addr     Local host bind address         <hostname> | <hostaddr>

  local_port     Local host bind port            <service> | <number>

  local_path     Local path for unix sockets     "/tmp/myserver.sock"

  domain         Socket domain name (or number)  "inet" | "inet6" | ...

  proto          Protocol name (or number)       "tcp" | "udp" | ...

  type           Socket type name (or number)    "stream" | "dgram" | ...

  listen         Put socket into listen state with a specified maximal number

                 of connections in the queue

  broadcast      Set SO_BROADCAST before binding

  reuseaddr      Set SO_REUSEADDR before binding

  blocking       Enable or disable blocking mode; default is enabled

  timeout        Timeout value for various operations as floating point number;

                 defaults to 15000 (15 seconds); currently used for connect

If local_addr, local_port or local_path is defined then the socket will bind a local address. If listen is defined then the socket will put into listen state. If remote_addr, remote_port or remote_path is defined then connect() is called.

Standard domain is AF_INET. Standard type is SOCK_STREAM. Standard proto is IPPROTO_TCP. If local_path or remote_path is defined the standard domain changes to AF_UNIX and the standard protocol changes to 0.

Examples

Create a nonblocking listening inet socket on a random local port


  $sock = Socket::Class->new(

      'listen' => 5,

      'blocking' => 0,

  ) or die Socket::Class->error;

  

  print "listen on local port ", $sock->local_port, "\n";

Create a listening unix socket


  $sock = Socket::Class->new(

      'domain' => 'unix',

      'local_path' => '/tmp/myserver.sock',

      'listen' => 5,

  ) or die Socket::Class->error;

Connect to smtp service (port 25) on localhost


  $sock = Socket::Class->new(

      'remote_addr' => 'localhost',

      'remote_addr' => 'smtp',

  ) or die Socket::Class->error;

Create a broadcast socket


  $sock = Socket::Class->new(

      'remote_addr' => "255.255.255.255",

      'remote_port' => 9999,

      'proto' => 'udp',

      'local_addr' => 'localhost',

      'broadcast' => 1,

  ) or die Socket::Class->error;

Closing / Destructing / Freeing

In non threaded applications an undef on the reference variable will free the socket and its resources.

In threaded applications, socket destruction by undefining the reference variable, wont work right anymore and has been disabled. In this case you need to call free().

shutdown ( [$how] )
Disables sends and receives on the socket.

Parameters

$how

One of the following values that specifies the operation that will no longer be allowed. Default is $SD_SEND.


  Num   Const         Description

  ----------------------------------------------------------------------

  0     $SD_SEND      Disable sending on the socket.

  1     $SD_RECEIVE   Disable receiving on the socket.

  2     $SD_BOTH      Disable both sending and receiving on the socket.

Return Values

Returns TRUE on succes or FALSE on failure. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  use Socket::Class qw($SD_BOTH);

  

  $sock = Socket::Class->new( ... );

  

  ...

  

  $sock->shutdown( $SD_BOTH );

  $sock->free();

close ()
Closes the socket without freeing internal resources.

free ()
Closes the socket and frees all internally allocated resources.

Bind and Accept

bind ( [$addr [, $port]] )
bind ( [$path] )
Binds the socket to a specified local address.

Parameters

$addr or $path

On 'inet' family sockets the $addr parameter can be an IP address in dotted-quad notation (e.g. 127.0.0.1) or a valid hostname.

On 'inet6' family sockets the $addr parameter can be an IPv6 address in hexadecimal notation (e.g. 2001:0db8:85a3:08d3:1319:8a2e:0370:7344) or a valid hostname.

On 'unix' family sockets the $path is the pathname of a Unix domain socket.

If $addr is not defined the address from last bind is used.

$port

The $port parameter designates the port or channel on the local host.

Return Values

Returns TRUE on succes or FALSE on failure. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $sock->bind( '0.0.0.0', 9999 )

      or die "can't bind: " . $sock->error;

accept ()
Accepts a connection on a bound socket. Once a successful connection is made, a new socket resource is returned, which may be used for communication. If there are multiple connections queued on the socket, the first will be used. If there are no pending connections, accept() will block until a connection becomes present. If socket has been made non-blocking using set_blocking(), 0 will be returned.

Return Values

Returns a new socket class on succes or 0 on non-blocking mode and no new connection becomes available or UNDEF on failure. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples

Blocking mode (default)


  while( $client = $sock->accept() ) {

      # do something with the connection

      print "Incoming connection: ", $client->to_string, "\n";

      ...

      $client->free();

  }

Non blocking mode


  while( 1 ) {

      $client = $sock->accept();

      if( ! defined $client ) {

          # error

          die $sock->error;

      }

      elsif( ! $client ) {

          # no client, sleep for a while

          $sock->wait( 10 );

          next;

      }

      # do something with the connection

      print "Incoming connection: ", $client->to_string, "\n";

      ...

      $client->free();

  }

Connect

connect ( [$addr [, $port [, $timeout]]] )
connect ( [$path [,$timeout]] )
Initiates a connection.

Parameters

$addr or $path

On 'inet' family sockets the $addr parameter can be an IP address in dotted-quad notation (e.g. 127.0.0.1) or a valid hostname.

On 'inet6' family sockets the $addr parameter can be an IPv6 address in hexadecimal notation (e.g. 2001:0db8:85a3:08d3:1319:8a2e:0370:7344) or a valid hostname.

On 'unix' family sockets the $path is the pathname of a Unix domain socket.

If $addr is not defined the address from last connect is used.

$port

The $port parameter designates the port or service on the remote host to which a connection should be made.

$timeout

Optionally timeout in milliseconds as floating point number.

Return Values

Returns a TRUE value on succes or UNDEF on failure. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $sock->connect( 'www.perl.org', 'http' )

      or die "can't connect: " . $sock->error;

reconnect ( [$timeout] )
Closes the current connection, waits $timeout milliseconds and reconnects the socket to the connection previously made.

Return Values

Returns a TRUE value on succes or UNDEF on failure. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  if( $sock->is_error ) {

  retry:

     print "socket error: ", $sock->error, "\n";

     # try to reconnect

     $r = $sock->reconnect( 1000 );

     if( ! $r ) {

         # can't connect

         goto retry;

     }

  }

Low level sending and receiving data

send ( $buf [, $flags] )
Sends data to a connected socket.

Parameters

$buf

A buffer containing the data that will be sent to the remote host.

$flags

The value of $flags can be any combination of the following:


  Number  Constant         Description

  -------------------------------------------------------------

  0x1     $MSG_OOB         Process OOB (out-of-band) data  

  0x2     $MSG_PEEK        Peek at incoming message  

  0x4     $MSG_DONTROUTE   Bypass routing, use direct interface  

  0x8     $MSG_CTRUNC      Data completes record  

  0x100   $MSG_WAITALL     Data completes transaction

Return Values

Returns the number of bytes sent or UNDEF if an error occured. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $r = $sock->send( "important message" );

  if( ! defined $r ) {

      # error

      die "can't sent: " . $sock->error;

  }

  print "sent $r bytes\n";

See Also

Socket::Class::Const

recv ( $buf, $len [, $flags] )
Receives data from a connected socket.

Parameters

$buf

A variable to write the received bytes into.

$len

The number of bytes to receive.

$flags

The value of $flags can be any combination of the following:


  Number  Constant         Description

  ---------------------------------------------------------------------------

  0x1     $MSG_OOB         Process OOB (out-of-band) data  

  0x2     $MSG_PEEK        Peek at incoming message  

  0x4     $MSG_DONTROUTE   Bypass routing, use direct interface  

  0x8     $MSG_CTRUNC      Data completes record

  0x20    $MSG_TRUNC       Return the real length of the packet, even when it

                           was longer than the passed buffer.

                           Only valid for packet sockets.

Return Values

Returns the number of bytes received or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

See Also

Socket::Class::Const

sendto ( $buf [, $to [, $flags]] )
Sends a message to a socket, whether it is connected or not.

Parameters

$buf

A buffer containing the data that will be sent to the remote host.

$to

Packed address of the remote host. (See pack_addr function)

$flags

The value of $flags can be any combination of the following:


  Number  Constant         Description

  -------------------------------------------------------------

  0x1     $MSG_OOB         Process OOB (out-of-band) data  

  0x2     $MSG_PEEK        Peek at incoming message  

  0x4     $MSG_DONTROUTE   Bypass routing, use direct interface

Return Values

Returns the bytes sent to the remote host or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $sock = Socket::Class->new( 'proto' => 'udp' );

  

  $paddr = $sock->pack_addr( 'localhost', 9999 );

  $sock->sendto( 'PING', $paddr );

OR


  $sock = Socket::Class->new(

      'proto' => 'udp',

      'remote_addr' => 'localhost',

      'remote_port' => 9999,

  );

  

  $sock->sento( 'PING' );

See Also

Socket::Class::Const

recvfrom ( $buf, $len [, $flags] )
Receives data from a socket whether or not it is connection-oriented

Parameters

$buf

The data received will be fetched to the variable specified with buf.

$len

Up to len bytes will be fetched from remote host.

$flags

The following table contains the different flags that can be set using the $flags parameter. Use the OR logic operator (|) to use more than one flag.


  Number  Constant         Description

  ---------------------------------------------------------------------------

  0x1     $MSG_OOB         Process OOB (out-of-band) data  

  0x2     $MSG_PEEK        Receive data from the beginning of the receive queue

                           without removing it from the queue.

  0x40    $MSG_DONTWAIT    With this flag set, the function returns even if it

                           would normally have blocked. 

  0x100   $MSG_WAITALL     Block until at least len are received. However,

                           if a signal is caught or the remote host

                           disconnects, the function may return less data.

Return Values

Returns a packed address of the sender or 0 on non-blocking mode and no data becomes available or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples

Blocking mode (default)


  while( $paddr = $sock->recvfrom( $buf, 1024 ) ) {

      ( $r_addr, $r_port ) = $sock->unpack_addr( $paddr );

      print "Incoming message from $r_addr port $r_port\n";

  }

Non blocking mode


  while( 1 ) {

      $paddr = $sock->recvfrom( $buf, 1024 );

      if( ! defined $paddr ) {

          # error

          die $sock->error;

      }

      elsif( ! $paddr ) {

          # no data, sleep for a while

          $sock->wait( 10 );

          next;

      }

      ( $r_addr, $r_port ) = $sock->unpack_addr( $paddr );

      print "Incoming message from $r_addr port $r_port\n";

  }

See Also

Socket::Class::Const

Higher level sending and receiving

write ( $buffer [, $length] )
Writes to the socket from the given buffer.

Parameters

$buffer

The buffer to be written.

$length

The optional parameter $length can specify an alternate length of bytes written to the socket. If this length is greater then the buffer length, it is silently truncated to the length of the buffer.

Return Values

Returns the number of bytes successfully written to the socket or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Notes

Note: write () does not necessarily write all bytes from the given buffer. It's valid that, depending on the network buffers etc., only a certain amount of data, even one byte, is written though your buffer is greater. You have to watch out so you don't unintentionally forget to transmit the rest of your data.

read ( $buffer, $length )
Reads a maximum of length bytes from a socket.

Parameters

$buffer

A variable to write the read bytes into.

$length

The maximum number of bytes read is specified by the length parameter.

Return Values

Returns number of bytes read or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

print ( ... )
Writes to the socket from the given parameters. print maps to write

Return Values

Returns the number of bytes successfully written to the socket or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $sock->print( 'hello client', "\n" );

printf ( $fmt, ... )
Writes formated string to the socket.

Parameters

$fmt

Defines the format of the string. See Perl printf and sprintf for more details

Return Values

Returns the number of bytes successfully written to the socket or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  # round number to 3 digits after decimal point and send it

  $sock->printf( "%.3f", $number );

  

  # does the same like above

  $sock->write( sprintf( "%.3f", $number ) );

say ( ... )
writeline ( ... )
Writes to the socket from the given string plus a newline char (\n). writeline is a synonym for say.

Return Values

Returns the number of bytes successfully written to the socket or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $sock->say( 'hello client' );

readline ()
Reads characters from the socket and stops at \n or \r\n.

Return Values

Returns a string value or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Socket options

set_blocking ( [$int] )
Sets blocking mode on the socket.

Parameters

$int

On 1 set blocking mode, on 0 set non-blocking mode.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_blocking ()
Returns the current blocking state.

Return Values

Return a TRUE value on blocking mode, or FALSE on non-blocking mode, or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_reuseaddr ( [$int] )
Sets the SO_REUSEADDR socket option.

Parameters

$int

On 1 enable reusaddr, on 0 disable reusaddr.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_reuseaddr ()
Returns the current value of SO_REUSEADDR.

Return Values

Return the value of SO_REUSEADDR or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_broadcast ( [$int] )
Sets the SO_BROADCAST socket option.

Parameters

$int

On 1 enable reusaddr, on 0 disable reusaddr.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_broadcast ()
Returns the current value of SO_BROADCAST.

Return Values

Return the value of SO_BROADCAST or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_rcvbuf_size ( [$size] )
Sets the SO_RCVBUF socket option.

Parameters

$size

The size of the receive buffer.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_rcvbuf_size ()
Returns the current value of SO_RCVBUF.

Return Values

Return the value of SO_RCVBUF or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_sndbuf_size ( [$size] )
Sets the SO_SNDBUF socket option.

Parameters

$size

The size of the send buffer.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_sndbuf_size ()
Returns the current value of SO_SNDBUF.

Return Values

Return the value of SO_SNDBUF or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_timeout ( [$ms] )
Sets the timeout for various operations.

Parameters

$ms

The timeout in milliseconds as floating point number.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_timeout ()
Returns the current timeout.

Return Values

Return the timeout in milliseconds or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_tcp_nodelay ( [$int] )
Sets the TCP_NODELAY socket option.

Parameters

$int

On 1 disable the naggle algorithm, on 0 enable it.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

get_tcp_nodelay ()
Returns the current value of TCP_NODELAY.

Return Values

Return the value of TCP_NODELAY or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

set_option ( $level, $optname, $optval, ... )
Sets socket options for the socket.

Parameters

$level

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level.

$optname

A valid socket option.

$optval ...

The option value in packed or unpacked format. If $optval is an integer value it will be packed as int. For SO_LINGER, SO_RCVTIMEO and SO_SNDTIMEO one or two values are accepted and are packed in the right format.

Return Values

Return a TRUE value on succes or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  use Socket::Class qw($SOL_SOCKET $SO_LINGER $SO_RCVTIMEO);

  

  $sock = Socket::Class->new( ... );

  

  # disable linger

  $sock->set_option( $SOL_SOCKET, $SO_LINGER, 0, 0 );

  # same like

  $sock->set_option( $SOL_SOCKET, $SO_LINGER, pack( 'S!S!', 0, 0 ) );

  

  # set rcv timeout to 0sec + 100000usec

  $sock->set_option( $SOL_SOCKET, $SO_RCVTIMEO, 0, 100000 );

  # or in milliseconds

  $sock->set_option( $SOL_SOCKET, $SO_RCVTIMEO, 100 );

See Also

Socket::Class::Const

get_option ( $level, $optname )
Gets socket options for the socket.

Parameters

$level

The level parameter specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level.

$optname

A valid socket option.


  Option             Description

  -----------------------------------------------------------------------------

  $SO_DEBUG          Reports whether debugging information is being recorded.  

  $SO_ACCEPTCONN     Reports whether socket listening is enabled.  

  $SO_BROADCAST      Reports whether transmission of broadcast messages is

                     supported.  

  $SO_REUSEADDR      Reports whether local addresses can be reused.  

  $SO_KEEPALIVE      Reports whether connections are kept active with periodic

                     transmission of messages. If the connected socket fails to

                     respond to these messages, the connection is broken and

                     processes writing to that socket are notified with a

                     SIGPIPE signal.  

  $SO_LINGER         Reports whether the socket lingers on close()

                     if data is present.  

  $SO_OOBINLINE      Reports whether the socket leaves out-of-band data inline.  

  $SO_SNDBUF         Reports send buffer size information.  

  $SO_RCVBUF         Reports recieve buffer size information.  

  $SO_ERROR          Reports information about error status and clears it.  

  $SO_TYPE           Reports the socket type.  

  $SO_DONTROUTE      Reports whether outgoing messages bypass the standard

                     routing facilities.  

  $SO_RCVLOWAT       Reports the minimum number of bytes to process for socket

                     input operations. ( Defaults to 1 )  

  $SO_RCVTIMEO       Reports the timeout value for input operations.  

  $SO_SNDLOWAT       Reports the minimum number of bytes to process for socket

                     output operations.  

  $SO_SNDTIMEO       Reports the timeout value specifying the amount of time

                     that an output function blocks because flow control

                     prevents data from being sent.

Return Values

Returns the value of the given option, or UNDEF on error. If the size of the value equals the size of int the value will be unpacked as integer. For SO_LINGER, SO_RCVTIMEO and SO_SNDTIMEO the value will be unpacked also. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  use Socket::Class qw($SOL_SOCKET $SO_LINGER $SO_RCVTIMEO);

  

  $sock = Socket::Class->new( ... );

  

  # get linger

  ( $l_onoff, $l_linger ) =

      $sock->get_option( $SOL_SOCKET, $SO_LINGER );

  

  # get rcv timeout

  ( $tv_sec, $tv_usec ) =

      $sock->get_option( $SOL_SOCKET, $SO_RCVTIMEO );

  # or in milliseconds

  $ms = $sock->get_option( $SOL_SOCKET, $SO_RCVTIMEO );

See Also

Socket::Class::Const

Address Functions

local_addr ()
Returns the local adress of the socket

local_port ()
Returns the local port of the socket

local_path ()
Returns the local path of 'unix' family sockets

remote_addr ()
Returns the remote adress of the socket

remote_port ()
Returns the remote port of the socket

remote_path ()
Returns the remote path of 'unix' family sockets

pack_addr ( $addr [, $port] )
Packs a given address and returns it.

Parameters

$addr

IP address on 'inet' family sockets or a unix path on 'unix' family sockets.

$port

Port number of the address.

Return Values

Returns a packed version of the given address.

Examples


  $paddr = $sock->pack_addr( 'localhost', 9999 );

  ( $addr, $port ) = $sock->unpack_addr( $paddr );

unpack_addr ( $paddr )
Unpacks a given address and returns it.

Parameters

$paddr

A packed address.

Return Values

Returns the unpacked version of the given address.

Examples


  $paddr = $sock->pack_addr( 'localhost', 9999 );

  ( $addr, $port ) = $sock->unpack_addr( $paddr );

get_hostname ( $addr )
Resolves the name of a given host address.

Parameters

$addr

The host address in plain (e.g. '192.168.0.1') or packed format.

Return Values

Returns the first hostname found, or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $str = $sock->get_hostname( '127.0.0.1' );

  

  # -or-

  

  $paddr = $sock->pack_addr( '127.0.0.1', 9999 );

  $str = $sock->get_hostname( $paddr );

get_hostaddr ( $name )
Resolves the address of a given host name.

Parameters

$name

The host name as a string.

Return Values

Returns the address of the host, or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Examples


  $host = 'www.perl.org';

  $addr = $sock->get_hostaddr( $host );

  print "address of $host is $addr\n";

Miscellaneous Functions

is_readable ( [$timeout] )
Does a read select on the socket and returns the result.

Parameters

$timeout

The timeout in milliseconds as a floating point value. If $timeout is initialized to 0, is_readable will return immediately; this is used to poll the readability of the socket. If the value is undef (no timeout), is_readable() can block indefinitely.

Return Values

Return 1 if the socket is readable, or 0 if it is not, or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

is_writable ( [$timeout] )
Does a write select on the socket and returns the result.

Parameters

$timeout

The timeout in milliseconds as a floating point value. If $timeout is initialized to 0, is_writable will return immediately; this is used to poll the writability of the socket. If the value is undef (no timeout), is_writable() can block indefinitely.

Return Values

Return 1 if the socket is writable, or 0 if it is not, or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

select ( [$read [, $write [, $except [, $timeout]]]] )
Runs the select() system call on the socket with a specified timeout.

Parameters

$read [in/out]

If the $read parameter is set, the socket will be watched to see if characters become available for reading. Out: Indicates the state of readability.

$write [in/out]

If the $write parameter is set, the socket will be watched to see if a write will not block. Out: Indicates the state of writability.

$except [in/out]

If the $except parameter is set, the socket will be watched for exceptions. Out: Indicates a socket exception.

$timeout

The timeout in milliseconds as a floating point value. If $timeout is initialized to 0, select will return immediately; this is used to poll the state of the socket. If the value is undef (no timeout), select() can block indefinitely.

Return Values

Returns a number between 0 to 3 which indicates the parameters set to TRUE, or UNDEF on error. The error code can be retrieved with errno() and the error string can be retrieved with error().

Remarks

In summary, the socket will be identified in a particular set when select returns if:

read:

  • If listen has been called and a connection is pending, accept will succeed.

  • Data is available for reading (includes OOB data if SO_OOBINLINE is enabled).

  • Connection has been closed/reset/terminated.

write:

  • If processing a connect call (nonblocking), connection has succeeded.

  • Data can be sent.

except:

  • If processing a connect call (nonblocking), connection attempt failed.

  • OOB data is available for reading (only if SO_OOBINLINE is disabled).

Examples


  # watch all states and return within 1 second

  $v = $sock->select( $r = 1, $w = 1, $e = 1, 1000 );

  if( ! defined $v ) {

      die $sock->error;

  }

  if( $e ) {

      # socket error

      $e = $sock->get_option( $SOL_SOCKET, $SO_ERROR );

      die $sock->error( $e );

  }

  if( $r ) {

      # socket is readable

      ...

  }

  if( $w ) {

      # socket is writable

      ...

  }
state ()
Returns the state of the socket.

Return Values


  Number   Constant         Description

  ---------------------------------------------------

  0        $SOS_INIT        Socket is created

  1        $SOS_BOUND       Socket is bound

  2        $SOS_LISTEN      Socket is listening

  3        $SOS_CONNECTED   Socket is connected

  4        $SOS_CLOSED      Socket is closed

  99       $SOS_ERROR       Socket got an error on last send or receive

to_string ()
Returns a readable version of the socket.

handle ()
fileno ()
Returns the internal socket handle. fileno is a synonym for handle.

wait ( $ms )
sleep ( $ms )
Sleeps the given number of milliseconds. sleep is a synonym for wait.

Parameters

$ms

The number of milliseconds to sleep.

Error handling

is_error ()
Indicates a socket error. Returns a true value on socket state SOS_ERROR, or a false value on other states.

errno ()
Returns the last error code.

error ( [code] )
Returns the error message of the error code provided by $code parameter, or from the last occurred error.


MORE EXAMPLES

Internet Server using Threads


  use threads;

  use threads::shared;

  

  use Socket::Class;

  

  our $RUNNING : shared = 1;

  

  our $Server = Socket::Class->new(

      'local_addr' => '0.0.0.0',

      'local_port' => 9999,

      'listen' => 30,

      'blocking' => 0,

      'reuseaddr' => 1,

  ) or die Socket::Class->error;

  

  # catch interrupt signals to provide clean shutdown

  $SIG{'INT'} = \&quit;

  #$SIG{'TERM'} = \&quit;

  

  threads->create( \&server_thread, $Server );

  

  while( $RUNNING ) {

      # do other things here

      # ...

      # sleep for a while

      $Server->wait( 100 );

  }

  

  1;

  

  sub quit {

      my( $thread );

      $RUNNING = 0;

      foreach $thread( threads->list ) {

          $thread->join();

      }

      $Server->free();

      exit( 0 );

  }

  

  sub server_thread {

      my( $server ) = @_;

      my( $client );

      print 'Server running at ' . $server->local_addr .

          ' port ' . $server->local_port . "\n";

      while( $RUNNING ) {

          $client = $server->accept();

          if( ! defined $client ) {

              # server is closed

              last;

          }

          elsif( ! $client ) {

              # no connection available, sleep for a while

              $server->wait( 10 );

              next;

          }

          threads->create( \&client_thread, $client );

      }

      return 1;

  }

  

  sub client_thread {

      my( $client ) = @_;

      my( $buf, $got );

      print 'Connection from ' . $client->remote_addr .

          ' port ' . $client->remote_port . "\n";

      # do something with the client

      $client->set_blocking( 0 );

      while( $RUNNING ) {

          $got = $client->read( $buf, 4096 );

          if( ! defined $got ) {

              # error

              warn $client->error;

              last;

          }

          elsif( ! $got ) {

              # no data available, sleep for a while

              $client->wait( 10 );

              next;

          }

          print "Got $got bytes from client\n";

          $client->write( 'thank you!' );

      }

      # close the client and free allocated resources

      $client->wait( 50 );

      $client->free();

      # detach thread

      threads->self->detach() if $RUNNING;

      return 1;

  }


AUTHORS

Christian Mueller <christian_at_hbr1.com>


COPYRIGHT

The Socket::Class module is free software. You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file.

Programminig
Wy
Wy
yW
Wy
Programming
Wy
Wy
Wy
Wy