xref: /openbsd-src/gnu/usr.bin/perl/dist/IO/lib/IO/Socket.pm (revision 3d61058aa5c692477b6d18acfbbdb653a9930ff9)
1
2# IO::Socket.pm
3#
4# Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved.
5# This program is free software; you can redistribute it and/or
6# modify it under the same terms as Perl itself.
7
8package IO::Socket;
9
10use 5.008_001;
11
12use IO::Handle;
13use Socket 1.3;
14use Carp;
15use strict;
16use Exporter;
17use Errno;
18
19# legacy
20
21require IO::Socket::INET;
22require IO::Socket::UNIX if ($^O ne 'epoc' && $^O ne 'symbian');
23
24our @ISA = qw(IO::Handle);
25
26our $VERSION = "1.55";
27
28our @EXPORT_OK = qw(sockatmark);
29
30our $errstr;
31
32sub import {
33    my $pkg = shift;
34    if (@_ && $_[0] eq 'sockatmark') { # not very extensible but for now, fast
35	Exporter::export_to_level('IO::Socket', 1, $pkg, 'sockatmark');
36    } else {
37	my $callpkg = caller;
38	Exporter::export 'Socket', $callpkg, @_;
39    }
40}
41
42sub new {
43    my($class,%arg) = @_;
44    my $sock = $class->SUPER::new();
45
46    $sock->autoflush(1);
47
48    ${*$sock}{'io_socket_timeout'} = delete $arg{Timeout};
49
50    return scalar(%arg) ? $sock->configure(\%arg)
51			: $sock;
52}
53
54my @domain2pkg;
55
56sub register_domain {
57    my($p,$d) = @_;
58    $domain2pkg[$d] = $p;
59}
60
61sub configure {
62    my($sock,$arg) = @_;
63    my $domain = delete $arg->{Domain};
64
65    croak 'IO::Socket: Cannot configure a generic socket'
66	unless defined $domain;
67
68    croak "IO::Socket: Unsupported socket domain"
69	unless defined $domain2pkg[$domain];
70
71    croak "IO::Socket: Cannot configure socket in domain '$domain'"
72	unless ref($sock) eq "IO::Socket";
73
74    bless($sock, $domain2pkg[$domain]);
75    $sock->configure($arg);
76}
77
78sub socket {
79    @_ == 4 or croak 'usage: $sock->socket(DOMAIN, TYPE, PROTOCOL)';
80    my($sock,$domain,$type,$protocol) = @_;
81
82    socket($sock,$domain,$type,$protocol) or
83    	return undef;
84
85    ${*$sock}{'io_socket_domain'} = $domain;
86    ${*$sock}{'io_socket_type'}   = $type;
87
88    # "A value of 0 for protocol will let the system select an
89    # appropriate protocol"
90    # so we need to look up what the system selected,
91    # not cache PF_UNSPEC.
92    ${*$sock}{'io_socket_proto'} = $protocol if $protocol;
93
94    $sock;
95}
96
97sub socketpair {
98    @_ == 4 || croak 'usage: IO::Socket->socketpair(DOMAIN, TYPE, PROTOCOL)';
99    my($class,$domain,$type,$protocol) = @_;
100    my $sock1 = $class->new();
101    my $sock2 = $class->new();
102
103    socketpair($sock1,$sock2,$domain,$type,$protocol) or
104    	return ();
105
106    ${*$sock1}{'io_socket_type'}  = ${*$sock2}{'io_socket_type'}  = $type;
107    ${*$sock1}{'io_socket_proto'} = ${*$sock2}{'io_socket_proto'} = $protocol;
108
109    ($sock1,$sock2);
110}
111
112sub connect {
113    @_ == 2 or croak 'usage: $sock->connect(NAME)';
114    my $sock = shift;
115    my $addr = shift;
116    my $timeout = ${*$sock}{'io_socket_timeout'};
117    my $err;
118    my $blocking;
119
120    $blocking = $sock->blocking(0) if $timeout;
121    if (!connect($sock, $addr)) {
122	if (defined $timeout && ($!{EINPROGRESS} || $!{EWOULDBLOCK})) {
123	    require IO::Select;
124
125	    my $sel = IO::Select->new( $sock );
126
127	    undef $!;
128	    my($r,$w,$e) = IO::Select::select(undef,$sel,$sel,$timeout);
129	    if(@$e[0]) {
130		# Windows return from select after the timeout in case of
131		# WSAECONNREFUSED(10061) if exception set is not used.
132		# This behavior is different from Linux.
133		# Using the exception
134		# set we now emulate the behavior in Linux
135		#    - Karthik Rajagopalan
136		$err = $sock->getsockopt(SOL_SOCKET,SO_ERROR);
137		$errstr = $@ = "connect: $err";
138	    }
139	    elsif(!@$w[0]) {
140		$err = $! || (exists &Errno::ETIMEDOUT ? &Errno::ETIMEDOUT : 1);
141		$errstr = $@ = "connect: timeout";
142	    }
143	    elsif (!connect($sock,$addr) &&
144                not ($!{EISCONN} || ($^O eq 'MSWin32' &&
145                ($! == (($] < 5.019004) ? 10022 : Errno::EINVAL))))
146            ) {
147		# Some systems refuse to re-connect() to
148		# an already open socket and set errno to EISCONN.
149		# Windows sets errno to WSAEINVAL (10022) (pre-5.19.4) or
150		# EINVAL (22) (5.19.4 onwards).
151		$err = $!;
152		$errstr = $@ = "connect: $!";
153	    }
154	}
155        elsif ($blocking || !($!{EINPROGRESS} || $!{EWOULDBLOCK}))  {
156	    $err = $!;
157	    $errstr = $@ = "connect: $!";
158	}
159    }
160
161    $sock->blocking(1) if $blocking;
162
163    $! = $err if $err;
164
165    $err ? undef : $sock;
166}
167
168# Enable/disable blocking IO on sockets.
169# Without args return the current status of blocking,
170# with args change the mode as appropriate, returning the
171# old setting, or in case of error during the mode change
172# undef.
173
174sub blocking {
175    my $sock = shift;
176
177    return $sock->SUPER::blocking(@_)
178        if $^O ne 'MSWin32' && $^O ne 'VMS';
179
180    # Windows handles blocking differently
181    #
182    # http://groups.google.co.uk/group/perl.perl5.porters/browse_thread/thread/b4e2b1d88280ddff/630b667a66e3509f?#630b667a66e3509f
183    # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/ioctlsocket_2.asp
184    #
185    # 0x8004667e is FIONBIO
186    #
187    # which is used to set blocking behaviour.
188
189    # NOTE:
190    # This is a little confusing, the perl keyword for this is
191    # 'blocking' but the OS level behaviour is 'non-blocking', probably
192    # because sockets are blocking by default.
193    # Therefore internally we have to reverse the semantics.
194
195    my $orig= !${*$sock}{io_sock_nonblocking};
196
197    return $orig unless @_;
198
199    my $block = shift;
200
201    if ( !$block != !$orig ) {
202        ${*$sock}{io_sock_nonblocking} = $block ? 0 : 1;
203        ioctl($sock, 0x8004667e, pack("L!",${*$sock}{io_sock_nonblocking}))
204            or return undef;
205    }
206
207    return $orig;
208}
209
210
211sub close {
212    @_ == 1 or croak 'usage: $sock->close()';
213    my $sock = shift;
214    ${*$sock}{'io_socket_peername'} = undef;
215    $sock->SUPER::close();
216}
217
218sub bind {
219    @_ == 2 or croak 'usage: $sock->bind(NAME)';
220    my $sock = shift;
221    my $addr = shift;
222
223    return bind($sock, $addr) ? $sock
224			      : undef;
225}
226
227sub listen {
228    @_ >= 1 && @_ <= 2 or croak 'usage: $sock->listen([QUEUE])';
229    my($sock,$queue) = @_;
230    $queue = 5
231	unless $queue && $queue > 0;
232
233    return listen($sock, $queue) ? $sock
234				 : undef;
235}
236
237sub accept {
238    @_ == 1 || @_ == 2 or croak 'usage $sock->accept([PKG])';
239    my $sock = shift;
240    my $pkg = shift || $sock;
241    my $timeout = ${*$sock}{'io_socket_timeout'};
242    my $new = $pkg->new(Timeout => $timeout);
243    my $peer = undef;
244
245    if(defined $timeout) {
246	require IO::Select;
247
248	my $sel = IO::Select->new( $sock );
249
250	unless ($sel->can_read($timeout)) {
251	    $errstr = $@ = 'accept: timeout';
252	    $! = (exists &Errno::ETIMEDOUT ? &Errno::ETIMEDOUT : 1);
253	    return;
254	}
255    }
256
257    $peer = accept($new,$sock)
258	or return;
259
260    ${*$new}{$_} = ${*$sock}{$_} for qw( io_socket_domain io_socket_type io_socket_proto );
261
262    return wantarray ? ($new, $peer)
263    	      	     : $new;
264}
265
266sub sockname {
267    @_ == 1 or croak 'usage: $sock->sockname()';
268    getsockname($_[0]);
269}
270
271sub peername {
272    @_ == 1 or croak 'usage: $sock->peername()';
273    my($sock) = @_;
274    ${*$sock}{'io_socket_peername'} ||= getpeername($sock);
275}
276
277sub connected {
278    @_ == 1 or croak 'usage: $sock->connected()';
279    my($sock) = @_;
280    getpeername($sock);
281}
282
283sub send {
284    @_ >= 2 && @_ <= 4 or croak 'usage: $sock->send(BUF, [FLAGS, [TO]])';
285    my $sock  = $_[0];
286    my $flags = $_[2] || 0;
287    my $peer;
288
289    if ($_[3]) {
290        # the caller explicitly requested a TO, so use it
291        # this is non-portable for "connected" UDP sockets
292        $peer = $_[3];
293    }
294    elsif (!defined getpeername($sock)) {
295        # we're not connected, so we require a peer from somewhere
296        $peer = $sock->peername;
297
298	croak 'send: Cannot determine peer address'
299	    unless(defined $peer);
300    }
301
302    my $r = $peer
303      ? send($sock, $_[1], $flags, $peer)
304      : send($sock, $_[1], $flags);
305
306    # remember who we send to, if it was successful
307    ${*$sock}{'io_socket_peername'} = $peer
308	if(@_ == 4 && defined $r);
309
310    $r;
311}
312
313sub recv {
314    @_ == 3 || @_ == 4 or croak 'usage: $sock->recv(BUF, LEN [, FLAGS])';
315    my $sock  = $_[0];
316    my $len   = $_[2];
317    my $flags = $_[3] || 0;
318
319    # remember who we recv'd from
320    ${*$sock}{'io_socket_peername'} = recv($sock, $_[1]='', $len, $flags);
321}
322
323sub shutdown {
324    @_ == 2 or croak 'usage: $sock->shutdown(HOW)';
325    my($sock, $how) = @_;
326    ${*$sock}{'io_socket_peername'} = undef;
327    shutdown($sock, $how);
328}
329
330sub setsockopt {
331    @_ == 4 or croak '$sock->setsockopt(LEVEL, OPTNAME, OPTVAL)';
332    setsockopt($_[0],$_[1],$_[2],$_[3]);
333}
334
335my $intsize = length(pack("i",0));
336
337sub getsockopt {
338    @_ == 3 or croak '$sock->getsockopt(LEVEL, OPTNAME)';
339    my $r = getsockopt($_[0],$_[1],$_[2]);
340    # Just a guess
341    $r = unpack("i", $r)
342	if(defined $r && length($r) == $intsize);
343    $r;
344}
345
346sub sockopt {
347    my $sock = shift;
348    @_ == 1 ? $sock->getsockopt(SOL_SOCKET,@_)
349	    : $sock->setsockopt(SOL_SOCKET,@_);
350}
351
352sub atmark {
353    @_ == 1 or croak 'usage: $sock->atmark()';
354    my($sock) = @_;
355    sockatmark($sock);
356}
357
358sub timeout {
359    @_ == 1 || @_ == 2 or croak 'usage: $sock->timeout([VALUE])';
360    my($sock,$val) = @_;
361    my $r = ${*$sock}{'io_socket_timeout'};
362
363    ${*$sock}{'io_socket_timeout'} = defined $val ? 0 + $val : $val
364	if(@_ == 2);
365
366    $r;
367}
368
369sub sockdomain {
370    @_ == 1 or croak 'usage: $sock->sockdomain()';
371    my $sock = shift;
372    if (!defined(${*$sock}{'io_socket_domain'})) {
373	my $addr = $sock->sockname();
374	${*$sock}{'io_socket_domain'} = sockaddr_family($addr)
375	    if (defined($addr));
376    }
377    ${*$sock}{'io_socket_domain'};
378}
379
380sub socktype {
381    @_ == 1 or croak 'usage: $sock->socktype()';
382    my $sock = shift;
383    ${*$sock}{'io_socket_type'} = $sock->sockopt(Socket::SO_TYPE)
384	if (!defined(${*$sock}{'io_socket_type'}) && defined(eval{Socket::SO_TYPE}));
385    ${*$sock}{'io_socket_type'}
386}
387
388sub protocol {
389    @_ == 1 or croak 'usage: $sock->protocol()';
390    my($sock) = @_;
391    ${*$sock}{'io_socket_proto'} = $sock->sockopt(Socket::SO_PROTOCOL)
392	if (!defined(${*$sock}{'io_socket_proto'}) && defined(eval{Socket::SO_PROTOCOL}));
393    ${*$sock}{'io_socket_proto'};
394}
395
3961;
397
398__END__
399
400=head1 NAME
401
402IO::Socket - Object interface to socket communications
403
404=head1 SYNOPSIS
405
406    use strict;
407    use warnings;
408
409    use IO::Socket qw(AF_INET AF_UNIX);
410
411    # create a new AF_INET socket
412    my $sock = IO::Socket->new(Domain => AF_INET);
413    # which is the same as
414    $sock = IO::Socket::INET->new();
415
416    # create a new AF_UNIX socket
417    $sock = IO::Socket->new(Domain => AF_UNIX);
418    # which is the same as
419    $sock = IO::Socket::UNIX->new();
420
421=head1 DESCRIPTION
422
423C<IO::Socket> provides an object-oriented, L<IO::Handle>-based interface to
424creating and using sockets via L<Socket>, which provides a near one-to-one
425interface to the C socket library.
426
427C<IO::Socket> is a base class that really only defines methods for those
428operations which are common to all types of sockets. Operations which are
429specific to a particular socket domain have methods defined in subclasses of
430C<IO::Socket>. See L<IO::Socket::INET>, L<IO::Socket::UNIX>, and
431L<IO::Socket::IP> for examples of such a subclass.
432
433C<IO::Socket> will export all functions (and constants) defined by L<Socket>.
434
435=head1 CONSTRUCTOR ARGUMENTS
436
437Given that C<IO::Socket> doesn't have attributes in the traditional sense, the
438following arguments, rather than attributes, can be passed into the
439constructor.
440
441Constructor arguments should be passed in C<< Key => 'Value' >> pairs.
442
443The only required argument is L<IO::Socket/"Domain">.
444
445=head2 Blocking
446
447    my $sock = IO::Socket->new(..., Blocking => 1);
448    $sock = IO::Socket->new(..., Blocking => 0);
449
450If defined but false, the socket will be set to non-blocking mode. If not
451specified it defaults to C<1> (blocking mode).
452
453=head2 Domain
454
455    my $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
456    $sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
457
458The socket domain will define which subclass of C<IO::Socket> to use. The two
459options available along with this distribution are C<AF_INET> and C<AF_UNIX>.
460
461C<AF_INET> is for the internet address family of sockets and is handled via
462L<IO::Socket::INET>. C<AF_INET> sockets are bound to an internet address and
463port.
464
465C<AF_UNIX> is for the unix domain socket and is handled via
466L<IO::Socket::UNIX>. C<AF_UNIX> sockets are bound to the file system as their
467address name space.
468
469This argument is B<required>. All other arguments are optional.
470
471=head2 Listen
472
473    my $sock = IO::Socket->new(..., Listen => 5);
474
475Listen should be an integer value or left unset.
476
477If provided, this argument will place the socket into listening mode. New
478connections can then be accepted using the L<IO::Socket/"accept"> method. The
479value given is used as the C<listen(2)> queue size.
480
481If the C<Listen> argument is given, but false, the queue size will be set to
4825.
483
484=head2 Timeout
485
486    my $sock = IO::Socket->new(..., Timeout => 5);
487
488The timeout value, in seconds, for this socket connection. How exactly this
489value is utilized is defined in the socket domain subclasses that make use of
490the value.
491
492=head2 Type
493
494    my $sock = IO::Socket->new(..., Type => IO::Socket::SOCK_STREAM);
495
496The socket type that will be used. These are usually C<SOCK_STREAM>,
497C<SOCK_DGRAM>, or C<SOCK_RAW>. If this argument is left undefined an attempt
498will be made to infer the type from the service name.
499
500For example, you'll usually use C<SOCK_STREAM> with a C<tcp> connection and
501C<SOCK_DGRAM> with a C<udp> connection.
502
503=head1 CONSTRUCTORS
504
505C<IO::Socket> extends the L<IO::Handle> constructor.
506
507=head2 new
508
509    my $sock = IO::Socket->new();
510
511    # get a new IO::Socket::INET instance
512    $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
513    # get a new IO::Socket::UNIX instance
514    $sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
515
516    # Domain is the only required argument
517    $sock = IO::Socket->new(
518        Domain => IO::Socket::AF_INET, # AF_INET, AF_UNIX
519        Type => IO::Socket::SOCK_STREAM, # SOCK_STREAM, SOCK_DGRAM, ...
520        Proto => 'tcp', # 'tcp', 'udp', IPPROTO_TCP, IPPROTO_UDP
521        # and so on...
522    );
523
524Creates an C<IO::Socket>, which is a reference to a newly created symbol (see
525the L<Symbol> package). C<new> optionally takes arguments, these arguments
526are defined in L<IO::Socket/"CONSTRUCTOR ARGUMENTS">.
527
528Any of the L<IO::Socket/"CONSTRUCTOR ARGUMENTS"> may be passed to the
529constructor, but if any arguments are provided, then one of them must be
530the L<IO::Socket/"Domain"> argument. The L<IO::Socket/"Domain"> argument can,
531by default, be either C<AF_INET> or C<AF_UNIX>. Other domains can be used if a
532proper subclass for the domain family is registered. All other arguments will
533be passed to the C<configuration> method of the package for that domain.
534
535If the constructor fails it will return C<undef> and set the C<$errstr> package
536variable to contain an error message.
537
538    $sock = IO::Socket->new(...)
539        or die "Cannot create socket - $IO::Socket::errstr\n";
540
541For legacy reasons the error message is also set into the global C<$@>
542variable, and you may still find older code which looks here instead.
543
544    $sock = IO::Socket->new(...)
545        or die "Cannot create socket - $@\n";
546
547=head1 METHODS
548
549C<IO::Socket> inherits all methods from L<IO::Handle> and implements the
550following new ones.
551
552=head2 accept
553
554    my $client_sock = $sock->accept();
555    my $inet_sock = $sock->accept('IO::Socket::INET');
556
557The accept method will perform the system call C<accept> on the socket and
558return a new object. The new object will be created in the same class as the
559listen socket, unless a specific package name is specified. This object can be
560used to communicate with the client that was trying to connect.
561
562This differs slightly from the C<accept> function in L<perlfunc>.
563
564In a scalar context the new socket is returned, or C<undef> upon
565failure. In a list context a two-element array is returned containing
566the new socket and the peer address; the list will be empty upon failure.
567
568=head2 atmark
569
570    my $integer = $sock->atmark();
571    # read in some data on a given socket
572    my $data;
573    $sock->read($data, 1024) until $sock->atmark;
574
575    # or, export the function to use:
576    use IO::Socket 'sockatmark';
577    $sock->read($data, 1024) until sockatmark($sock);
578
579True if the socket is currently positioned at the urgent data mark, false
580otherwise. If your system doesn't yet implement C<sockatmark> this will throw
581an exception.
582
583If your system does not support C<sockatmark>, the C<use> declaration will
584fail at compile time.
585
586=head2 autoflush
587
588    # by default, autoflush will be turned on when referenced
589    $sock->autoflush(); # turns on autoflush
590    # turn off autoflush
591    $sock->autoflush(0);
592    # turn on autoflush
593    $sock->autoflush(1);
594
595This attribute isn't overridden from L<IO::Handle>'s implementation. However,
596since we turn it on by default, it's worth mentioning here.
597
598=head2 bind
599
600    use Socket qw(pack_sockaddr_in);
601    my $port = 3000;
602    my $ip_address = '0.0.0.0';
603    my $packed_addr = pack_sockaddr_in($port, $ip_address);
604    $sock->bind($packed_addr);
605
606Binds a network address to a socket, just as C<bind(2)> does. Returns true if
607it succeeded, false otherwise. You should provide a packed address of the
608appropriate type for the socket.
609
610=head2 connected
611
612    my $peer_addr = $sock->connected();
613    if ($peer_addr) {
614        say "We're connected to $peer_addr";
615    }
616
617If the socket is in a connected state, the peer address is returned. If the
618socket is not in a connected state, C<undef> is returned.
619
620Note that this method considers a half-open TCP socket to be "in a connected
621state".  Specifically, it does not distinguish between the
622B<ESTABLISHED> and B<CLOSE-WAIT> TCP states; it returns the peer address,
623rather than C<undef>, in either case.  Thus, in general, it cannot
624be used to reliably learn whether the peer has initiated a graceful shutdown
625because in most cases (see below) the local TCP state machine remains in
626B<CLOSE-WAIT> until the local application calls L<IO::Socket/"shutdown"> or
627C<close>. Only at that point does this function return C<undef>.
628
629The "in most cases" hedge is because local TCP state machine behavior may
630depend on the peer's socket options. In particular, if the peer socket has
631C<SO_LINGER> enabled with a zero timeout, then the peer's C<close> will
632generate a C<RST> segment. Upon receipt of that segment, the local TCP
633transitions immediately to B<CLOSED>, and in that state, this method I<will>
634return C<undef>.
635
636=head2 getsockopt
637
638    my $value = $sock->getsockopt(SOL_SOCKET, SO_REUSEADDR);
639    my $buf = $socket->getsockopt(SOL_SOCKET, SO_RCVBUF);
640    say "Receive buffer is $buf bytes";
641
642Get an option associated with the socket. Levels other than C<SOL_SOCKET>
643may be specified here. As a convenience, this method will unpack a byte buffer
644of the correct size back into a number.
645
646=head2 listen
647
648    $sock->listen(5);
649
650Does the same thing that the C<listen(2)> system call does. Returns true if it
651succeeded, false otherwise. Listens to a socket with a given queue size.
652
653=head2 peername
654
655    my $sockaddr_in = $sock->peername();
656
657Returns the packed C<sockaddr> address of the other end of the socket
658connection. It calls C<getpeername>.
659
660
661=head2 protocol
662
663    my $proto = $sock->protocol();
664
665Returns the number for the protocol being used on the socket, if
666known. If the protocol is unknown, as with an C<AF_UNIX> socket, zero
667is returned.
668
669=head2 recv
670
671    my $buffer = "";
672    my $length = 1024;
673    my $flags = 0; # default. optional
674    $sock->recv($buffer, $length);
675    $sock->recv($buffer, $length, $flags);
676
677Similar in functionality to L<perlfunc/recv>.
678
679Receives a message on a socket. Attempts to receive C<$length> characters of
680data into C<$buffer> from the specified socket. C<$buffer> will be grown or
681shrunk to the length actually read. Takes the same flags as the system call of
682the same name. Returns the address of the sender if socket's protocol supports
683this; returns an empty string otherwise. If there's an error, returns
684C<undef>. This call is actually implemented in terms of the C<recvfrom(2)>
685system call.
686
687Flags are ORed together values, such as C<MSG_BCAST>, C<MSG_OOB>,
688C<MSG_TRUNC>. The default value for the flags is C<0>.
689
690The cached value of L<IO::Socket/"peername"> is updated with the result of
691C<recv>.
692
693B<Note:> In Perl v5.30 and newer, if the socket has been marked as C<:utf8>,
694C<recv> will throw an exception. The C<:encoding(...)> layer implicitly
695introduces the C<:utf8> layer. See L<perlfunc/binmode>.
696
697B<Note:> In Perl versions older than v5.30, depending on the status of the
698socket, either (8-bit) bytes or characters are received. By default all
699sockets operate on bytes, but for example if the socket has been changed
700using L<perlfunc/binmode> to operate with the C<:encoding(UTF-8)> I/O layer
701(see the L<perlfunc/open> pragma), the I/O will operate on UTF8-encoded
702Unicode characters, not bytes. Similarly for the C<:encoding> layer: in
703that case pretty much any characters can be read.
704
705=head2 send
706
707    my $message = "Hello, world!";
708    my $flags = 0; # defaults to zero
709    my $to = '0.0.0.0'; # optional destination
710    my $sent = $sock->send($message);
711    $sent = $sock->send($message, $flags);
712    $sent = $sock->send($message, $flags, $to);
713
714Similar in functionality to L<perlfunc/send>.
715
716Sends a message on a socket. Attempts to send the scalar message to the
717socket. Takes the same flags as the system call of the same name. On
718unconnected sockets, you must specify a destination to send to, in which case
719it does a C<sendto(2)> syscall. Returns the number of characters sent, or
720C<undef> on error. The C<sendmsg(2)> syscall is currently unimplemented.
721
722The C<flags> option is optional and defaults to C<0>.
723
724After a successful send with C<$to>, further calls to C<send> on an
725unconnected socket without C<$to> will send to the same address, and C<$to>
726will be used as the result of L<IO::Socket/"peername">.
727
728B<Note:> In Perl v5.30 and newer, if the socket has been marked as C<:utf8>,
729C<send> will throw an exception. The C<:encoding(...)> layer implicitly
730introduces the C<:utf8> layer. See L<perlfunc/binmode>.
731
732B<Note:> In Perl versions older than v5.30, depending on the status of the
733socket, either (8-bit) bytes or characters are sent. By default all
734sockets operate on bytes, but for example if the socket has been changed
735using L<perlfunc/binmode> to operate with the C<:encoding(UTF-8)> I/O layer
736(see the L<perlfunc/open> pragma), the I/O will operate on UTF8-encoded
737Unicode characters, not bytes. Similarly for the C<:encoding> layer: in
738that case pretty much any characters can be sent.
739
740=head2 setsockopt
741
742    $sock->setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
743    $sock->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024);
744
745Set option associated with the socket. Levels other than C<SOL_SOCKET>
746may be specified here. As a convenience, this method will convert a number
747into a packed byte buffer.
748
749=head2 shutdown
750
751    $sock->shutdown(SHUT_RD); # we stopped reading data
752    $sock->shutdown(SHUT_WR); # we stopped writing data
753    $sock->shutdown(SHUT_RDWR); # we stopped using this socket
754
755Shuts down a socket connection in the manner indicated by the value passed in,
756which has the same interpretation as in the syscall of the same name.
757
758This is useful with sockets when you want to tell the other side you're done
759writing but not done reading, or vice versa. It's also a more insistent form
760of C<close> because it also disables the file descriptor in any
761forked copies in other processes.
762
763Returns C<1> for success; on error, returns C<undef> if the socket is
764not a valid filehandle, or returns C<0> and sets C<$!> for any other failure.
765
766=head2 sockdomain
767
768    my $domain = $sock->sockdomain();
769
770Returns the number for the socket domain type. For example, for
771an C<AF_INET> socket the value of C<&AF_INET> will be returned.
772
773=head2 socket
774
775    my $sock = IO::Socket->new(); # no values given
776    # now let's actually get a socket with the socket method
777    # domain, type, and protocol are required
778    $sock = $sock->socket(AF_INET, SOCK_STREAM, 'tcp');
779
780Opens a socket of the specified kind and returns it. Domain, type, and
781protocol are specified the same as for the syscall of the same name.
782
783=head2 socketpair
784
785    my ($r, $w) = $sock->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
786    ($r, $w) = IO::Socket::UNIX
787        ->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
788
789Will return a list of two sockets created (read and write), or an empty list
790on failure.
791
792Differs slightly from C<socketpair> in L<perlfunc> in that the argument list
793is a bit simpler.
794
795=head2 sockname
796
797    my $packed_addr = $sock->sockname();
798
799Returns the packed C<sockaddr> address of this end of the connection. It's the
800same as C<getsockname(2)>.
801
802=head2 sockopt
803
804    my $value = $sock->sockopt(SO_REUSEADDR);
805    $sock->sockopt(SO_REUSEADDR, 1);
806
807Unified method to both set and get options in the C<SOL_SOCKET> level. If
808called with one argument then L<IO::Socket/"getsockopt"> is called, otherwise
809L<IO::Socket/"setsockopt"> is called.
810
811=head2 socktype
812
813    my $type = $sock->socktype();
814
815Returns the number for the socket type. For example, for
816a C<SOCK_STREAM> socket the value of C<&SOCK_STREAM> will be returned.
817
818=head2 timeout
819
820    my $seconds = $sock->timeout();
821    my $old_val = $sock->timeout(5); # set new and return old value
822
823Set or get the timeout value (in seconds) associated with this socket.
824If called without any arguments then the current setting is returned. If
825called with an argument the current setting is changed and the previous
826value returned.
827
828This method is available to all C<IO::Socket> implementations but may or may
829not be used by the individual domain subclasses.
830
831=head1 EXAMPLES
832
833Let's create a TCP server on C<localhost:3333>.
834
835    use strict;
836    use warnings;
837    use feature 'say';
838
839    use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
840
841    my $server = IO::Socket->new(
842        Domain => AF_INET,
843        Type => SOCK_STREAM,
844        Proto => 'tcp',
845        LocalHost => '0.0.0.0',
846        LocalPort => 3333,
847        ReusePort => 1,
848        Listen => 5,
849    ) || die "Can't open socket: $IO::Socket::errstr";
850    say "Waiting on 3333";
851
852    while (1) {
853        # waiting for a new client connection
854        my $client = $server->accept();
855
856        # get information about a newly connected client
857        my $client_address = $client->peerhost();
858        my $client_port = $client->peerport();
859        say "Connection from $client_address:$client_port";
860
861        # read up to 1024 characters from the connected client
862        my $data = "";
863        $client->recv($data, 1024);
864        say "received data: $data";
865
866        # write response data to the connected client
867        $data = "ok";
868        $client->send($data);
869
870        # notify client that response has been sent
871        $client->shutdown(SHUT_WR);
872    }
873
874    $server->close();
875
876A client for such a server could be
877
878    use strict;
879    use warnings;
880    use feature 'say';
881
882    use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
883
884    my $client = IO::Socket->new(
885        Domain => AF_INET,
886        Type => SOCK_STREAM,
887        proto => 'tcp',
888        PeerPort => 3333,
889        PeerHost => '0.0.0.0',
890    ) || die "Can't open socket: $IO::Socket::errstr";
891
892    say "Sending Hello World!";
893    my $size = $client->send("Hello World!");
894    say "Sent data of length: $size";
895
896    $client->shutdown(SHUT_WR);
897
898    my $buffer;
899    $client->recv($buffer, 1024);
900    say "Got back $buffer";
901
902    $client->close();
903
904
905=head1 LIMITATIONS
906
907On some systems, for an IO::Socket object created with C<new_from_fd>,
908or created with L<IO::Socket/"accept"> from such an object, the
909L<IO::Socket/"protocol">, L<IO::Socket/"sockdomain"> and
910L<IO::Socket/"socktype"> methods may return C<undef>.
911
912=head1 SEE ALSO
913
914L<Socket>, L<IO::Handle>, L<IO::Socket::INET>, L<IO::Socket::UNIX>,
915L<IO::Socket::IP>
916
917=head1 AUTHOR
918
919Graham Barr.  atmark() by Lincoln Stein.  Currently maintained by the Perl 5
920Porters.  Please report all bugs at L<https://github.com/Perl/perl5/issues>.
921
922=head1 COPYRIGHT
923
924Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights reserved.
925This program is free software; you can redistribute it and/or
926modify it under the same terms as Perl itself.
927
928The atmark() implementation: Copyright 2001, Lincoln Stein <lstein@cshl.org>.
929This module is distributed under the same terms as Perl itself.
930Feel free to use, modify and redistribute it as long as you retain
931the correct attribution.
932
933=cut
934