Perl 5 version 32.0 documentation

IO::Socket

NAME

IO::Socket - Object interface to socket communications

SYNOPSIS

  1. use strict;
  2. use warnings;
  3. use IO::Socket qw(AF_INET AF_UNIX);
  4. # create a new AF_INET socket
  5. my $sock = IO::Socket->new(Domain => AF_INET);
  6. # which is the same as
  7. $sock = IO::Socket::INET->new();
  8. # create a new AF_UNIX socket
  9. $sock = IO::Socket->new(Domain => AF_UNIX);
  10. # which is the same as
  11. $sock = IO::Socket::UNIX->new();

DESCRIPTION

IO::Socket provides an object-oriented, IO::Handle-based interface to creating and using sockets via Socket, which provides a near one-to-one interface to the C socket library.

IO::Socket is a base class that really only defines methods for those operations which are common to all types of sockets. Operations which are specific to a particular socket domain have methods defined in subclasses of IO::Socket . See IO::Socket::INET, IO::Socket::UNIX, and IO::Socket::IP for examples of such a subclass.

IO::Socket will export all functions (and constants) defined by Socket.

CONSTRUCTOR ARGUMENTS

Given that IO::Socket doesn't have attributes in the traditional sense, the following arguments, rather than attributes, can be passed into the constructor.

Constructor arguments should be passed in Key => 'Value' pairs.

The only required argument is Domain in IO::Socket.

Blocking

  1. my $sock = IO::Socket->new(..., Blocking => 1);
  2. $sock = IO::Socket->new(..., Blocking => 0);

If defined but false, the socket will be set to non-blocking mode. If not specified it defaults to 1 (blocking mode).

Domain

  1. my $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
  2. $sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);

The socket domain will define which subclass of IO::Socket to use. The two options available along with this distribution are AF_INET and AF_UNIX .

AF_INET is for the internet address family of sockets and is handled via IO::Socket::INET. AF_INET sockets are bound to an internet address and port.

AF_UNIX is for the unix domain socket and is handled via IO::Socket::UNIX. AF_UNIX sockets are bound to the file system as their address name space.

This argument is required. All other arguments are optional.

Listen

  1. my $sock = IO::Socket->new(..., Listen => 5);

Listen should be an integer value or left unset.

If provided, this argument will place the socket into listening mode. New connections can then be accepted using the accept in IO::Socket method. The value given is used as the listen(2) queue size.

If the Listen argument is given, but false, the queue size will be set to 5.

Timeout

  1. my $sock = IO::Socket->new(..., Timeout => 5);

The timeout value, in seconds, for this socket connection. How exactly this value is utilized is defined in the socket domain subclasses that make use of the value.

Type

  1. my $sock = IO::Socket->new(..., Type => IO::Socket::SOCK_STREAM);

The socket type that will be used. These are usually SOCK_STREAM , SOCK_DGRAM , or SOCK_RAW . If this argument is left undefined an attempt will be made to infer the type from the service name.

For example, you'll usually use SOCK_STREAM with a tcp connection and SOCK_DGRAM with a udp connection.

CONSTRUCTORS

IO::Socket extends the IO::Handle constructor.

new

  1. my $sock = IO::Socket->new();
  2. # get a new IO::Socket::INET instance
  3. $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
  4. # get a new IO::Socket::UNIX instance
  5. $sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
  6. # Domain is the only required argument
  7. $sock = IO::Socket->new(
  8. Domain => IO::Socket::AF_INET, # AF_INET, AF_UNIX
  9. Type => IO::Socket::SOCK_STREAM, # SOCK_STREAM, SOCK_DGRAM, ...
  10. Proto => 'tcp', # 'tcp', 'udp', IPPROTO_TCP, IPPROTO_UDP
  11. # and so on...
  12. );

Creates an IO::Socket , which is a reference to a newly created symbol (see the Symbol package). new optionally takes arguments, these arguments are defined in CONSTRUCTOR ARGUMENTS in IO::Socket.

Any of the CONSTRUCTOR ARGUMENTS in IO::Socket may be passed to the constructor, but if any arguments are provided, then one of them must be the Domain in IO::Socket argument. The Domain in IO::Socket argument can, by default, be either AF_INET or AF_UNIX . Other domains can be used if a proper subclass for the domain family is registered. All other arguments will be passed to the configuration method of the package for that domain.

METHODS

IO::Socket inherits all methods from IO::Handle and implements the following new ones.

accept

  1. my $client_sock = $sock->accept();
  2. my $inet_sock = $sock->accept('IO::Socket::INET');

The accept method will perform the system call accept on the socket and return a new object. The new object will be created in the same class as the listen socket, unless a specific package name is specified. This object can be used to communicate with the client that was trying to connect.

This differs slightly from the accept function in perlfunc.

In a scalar context the new socket is returned, or undef upon failure. In a list context a two-element array is returned containing the new socket and the peer address; the list will be empty upon failure.

atmark

  1. my $integer = $sock->atmark();
  2. # read in some data on a given socket
  3. my $data;
  4. $sock->read($data, 1024) until $sock->atmark;
  5. # or, export the function to use:
  6. use IO::Socket 'sockatmark';
  7. $sock->read($data, 1024) until sockatmark($sock);

True if the socket is currently positioned at the urgent data mark, false otherwise. If your system doesn't yet implement sockatmark this will throw an exception.

If your system does not support sockatmark , the use declaration will fail at compile time.

autoflush

  1. # by default, autoflush will be turned on when referenced
  2. $sock->autoflush(); # turns on autoflush
  3. # turn off autoflush
  4. $sock->autoflush(0);
  5. # turn on autoflush
  6. $sock->autoflush(1);

This attribute isn't overridden from IO::Handle's implementation. However, since we turn it on by default, it's worth mentioning here.

bind

  1. use Socket qw(pack_sockaddr_in);
  2. my $port = 3000;
  3. my $ip_address = '0.0.0.0';
  4. my $packed_addr = pack_sockaddr_in($port, $ip_address);
  5. $sock->bind($packed_addr);

Binds a network address to a socket, just as bind(2) does. Returns true if it succeeded, false otherwise. You should provide a packed address of the appropriate type for the socket.

connected

  1. my $peer_addr = $sock->connected();
  2. if ($peer_addr) {
  3. say "We're connected to $peer_addr";
  4. }

If the socket is in a connected state, the peer address is returned. If the socket is not in a connected state, undef is returned.

Note that this method considers a half-open TCP socket to be "in a connected state". Specifically, it does not distinguish between the ESTABLISHED and CLOSE-WAIT TCP states; it returns the peer address, rather than undef, in either case. Thus, in general, it cannot be used to reliably learn whether the peer has initiated a graceful shutdown because in most cases (see below) the local TCP state machine remains in CLOSE-WAIT until the local application calls shutdown in IO::Socket or close. Only at that point does this function return undef.

The "in most cases" hedge is because local TCP state machine behavior may depend on the peer's socket options. In particular, if the peer socket has SO_LINGER enabled with a zero timeout, then the peer's close will generate a RST segment. Upon receipt of that segment, the local TCP transitions immediately to CLOSED, and in that state, this method will return undef.

getsockopt

  1. my $value = $sock->getsockopt(SOL_SOCKET, SO_REUSEADDR);
  2. my $buf = $socket->getsockopt(SOL_SOCKET, SO_RCVBUF);
  3. say "Receive buffer is $buf bytes";

Get an option associated with the socket. Levels other than SOL_SOCKET may be specified here. As a convenience, this method will unpack a byte buffer of the correct size back into a number.

listen

  1. $sock->listen(5);

Does the same thing that the listen(2) system call does. Returns true if it succeeded, false otherwise. Listens to a socket with a given queue size.

peername

  1. my $sockaddr_in = $sock->peername();

Returns the packed sockaddr address of the other end of the socket connection. It calls getpeername.

protocol

  1. my $proto = $sock->protocol();

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

recv

  1. my $buffer = "";
  2. my $length = 1024;
  3. my $flags = 0; # default. optional
  4. $sock->recv($buffer, $length);
  5. $sock->recv($buffer, $length, $flags);

Similar in functionality to recv.

Receives a message on a socket. Attempts to receive $length characters of data into $buffer from the specified socket. $buffer will be grown or shrunk to the length actually read. Takes the same flags as the system call of the same name. Returns the address of the sender if socket's protocol supports this; returns an empty string otherwise. If there's an error, returns undef. This call is actually implemented in terms of the recvfrom(2) system call.

Flags are ORed together values, such as MSG_BCAST , MSG_OOB , MSG_TRUNC . The default value for the flags is .

The cached value of peername in IO::Socket is updated with the result of recv.

Note: In Perl v5.30 and newer, if the socket has been marked as :utf8 , recv will throw an exception. The :encoding(...) layer implicitly introduces the :utf8 layer. See binmode.

Note: In Perl versions older than v5.30, depending on the status of the socket, either (8-bit) bytes or characters are received. By default all sockets operate on bytes, but for example if the socket has been changed using binmode to operate with the :encoding(UTF-8) I/O layer (see the open pragma), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the :encoding layer: in that case pretty much any characters can be read.

send

  1. my $message = "Hello, world!";
  2. my $flags = 0; # defaults to zero
  3. my $to = '0.0.0.0'; # optional destination
  4. my $sent = $sock->send($message);
  5. $sent = $sock->send($message, $flags);
  6. $sent = $sock->send($message, $flags, $to);

Similar in functionality to send.

Sends a message on a socket. Attempts to send the scalar message to the socket. Takes the same flags as the system call of the same name. On unconnected sockets, you must specify a destination to send to, in which case it does a sendto(2) syscall. Returns the number of characters sent, or undef on error. The sendmsg(2) syscall is currently unimplemented.

The flags option is optional and defaults to .

After a successful send with $to , further calls to send on an unconnected socket without $to will send to the same address, and $to will be used as the result of peername in IO::Socket.

Note: In Perl v5.30 and newer, if the socket has been marked as :utf8 , send will throw an exception. The :encoding(...) layer implicitly introduces the :utf8 layer. See binmode.

Note: In Perl versions older than v5.30, depending on the status of the socket, either (8-bit) bytes or characters are sent. By default all sockets operate on bytes, but for example if the socket has been changed using binmode to operate with the :encoding(UTF-8) I/O layer (see the open pragma), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the :encoding layer: in that case pretty much any characters can be sent.

setsockopt

  1. $sock->setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
  2. $sock->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024);

Set option associated with the socket. Levels other than SOL_SOCKET may be specified here. As a convenience, this method will convert a number into a packed byte buffer.

shutdown

  1. $sock->shutdown(SHUT_RD); # we stopped reading data
  2. $sock->shutdown(SHUT_WR); # we stopped writing data
  3. $sock->shutdown(SHUT_RDWR); # we stopped using this socket

Shuts down a socket connection in the manner indicated by the value passed in, which has the same interpretation as in the syscall of the same name.

This is useful with sockets when you want to tell the other side you're done writing but not done reading, or vice versa. It's also a more insistent form of close because it also disables the file descriptor in any forked copies in other processes.

Returns 1 for success; on error, returns undef if the socket is not a valid filehandle, or returns and sets $! for any other failure.

sockdomain

  1. my $domain = $sock->sockdomain();

Returns the number for the socket domain type. For example, for an AF_INET socket the value of &AF_INET will be returned.

socket

  1. my $sock = IO::Socket->new(); # no values given
  2. # now let's actually get a socket with the socket method
  3. # domain, type, and protocol are required
  4. $sock = $sock->socket(AF_INET, SOCK_STREAM, 'tcp');

Opens a socket of the specified kind and returns it. Domain, type, and protocol are specified the same as for the syscall of the same name.

socketpair

  1. my ($r, $w) = $sock->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
  2. ($r, $w) = IO::Socket::UNIX
  3. ->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);

Will return a list of two sockets created (read and write), or an empty list on failure.

Differs slightly from socketpair in perlfunc in that the argument list is a bit simpler.

sockname

  1. my $packed_addr = $sock->sockname();

Returns the packed sockaddr address of this end of the connection. It's the same as getsockname(2).

sockopt

  1. my $value = $sock->sockopt(SO_REUSEADDR);
  2. $sock->sockopt(SO_REUSEADDR, 1);

Unified method to both set and get options in the SOL_SOCKET level. If called with one argument then getsockopt in IO::Socket is called, otherwise setsockopt in IO::Socket is called.

socktype

  1. my $type = $sock->socktype();

Returns the number for the socket type. For example, for a SOCK_STREAM socket the value of &SOCK_STREAM will be returned.

timeout

  1. my $seconds = $sock->timeout();
  2. my $old_val = $sock->timeout(5); # set new and return old value

Set or get the timeout value (in seconds) associated with this socket. If called without any arguments then the current setting is returned. If called with an argument the current setting is changed and the previous value returned.

This method is available to all IO::Socket implementations but may or may not be used by the individual domain subclasses.

EXAMPLES

Let's create a TCP server on localhost:3333 .

  1. use strict;
  2. use warnings;
  3. use feature 'say';
  4. use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
  5. my $server = IO::Socket->new(
  6. Domain => AF_INET,
  7. Type => SOCK_STREAM,
  8. Proto => 'tcp',
  9. LocalHost => '0.0.0.0',
  10. LocalPort => 3333,
  11. ReusePort => 1,
  12. Listen => 5,
  13. ) || die "Can't open socket: $@";
  14. say "Waiting on 3333";
  15. while (1) {
  16. # waiting for a new client connection
  17. my $client = $server->accept();
  18. # get information about a newly connected client
  19. my $client_address = $client->peerhost();
  20. my $client_port = $client->peerport();
  21. say "Connection from $client_address:$client_port";
  22. # read up to 1024 characters from the connected client
  23. my $data = "";
  24. $client->recv($data, 1024);
  25. say "received data: $data";
  26. # write response data to the connected client
  27. $data = "ok";
  28. $client->send($data);
  29. # notify client that response has been sent
  30. $client->shutdown(SHUT_WR);
  31. }
  32. $server->close();

A client for such a server could be

  1. use strict;
  2. use warnings;
  3. use feature 'say';
  4. use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
  5. my $client = IO::Socket->new(
  6. Domain => AF_INET,
  7. Type => SOCK_STREAM,
  8. proto => 'tcp',
  9. PeerPort => 3333,
  10. PeerHost => '0.0.0.0',
  11. ) || die "Can't open socket: $@";
  12. say "Sending Hello World!";
  13. my $size = $client->send("Hello World!");
  14. say "Sent data of length: $size";
  15. $client->shutdown(SHUT_WR);
  16. my $buffer;
  17. $client->recv($buffer, 1024);
  18. say "Got back $buffer";
  19. $client->close();

LIMITATIONS

On some systems, for an IO::Socket object created with new_from_fd , or created with accept in IO::Socket from such an object, the protocol in IO::Socket, sockdomain in IO::Socket and socktype in IO::Socket methods may return undef.

SEE ALSO

Socket, IO::Handle, IO::Socket::INET, IO::Socket::UNIX, IO::Socket::IP

AUTHOR

Graham Barr. atmark() by Lincoln Stein. Currently maintained by the Perl Porters. Please report all bugs to <perlbug@perl.org>.

COPYRIGHT

Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The atmark() implementation: Copyright 2001, Lincoln Stein <lstein@cshl.org>. This module is distributed under the same terms as Perl itself. Feel free to use, modify and redistribute it as long as you retain the correct attribution.