1IO::Socket(3pm) Perl Programmers Reference Guide IO::Socket(3pm)
2
3
4
6 IO::Socket - Object interface to socket communications
7
9 use strict;
10 use warnings;
11
12 use IO::Socket qw(AF_INET AF_UNIX);
13
14 # create a new AF_INET socket
15 my $sock = IO::Socket->new(Domain => AF_INET);
16 # which is the same as
17 $sock = IO::Socket::INET->new();
18
19 # create a new AF_UNIX socket
20 $sock = IO::Socket->new(Domain => AF_UNIX);
21 # which is the same as
22 $sock = IO::Socket::UNIX->new();
23
25 "IO::Socket" provides an object-oriented, IO::Handle-based interface to
26 creating and using sockets via Socket, which provides a near one-to-one
27 interface to the C socket library.
28
29 "IO::Socket" is a base class that really only defines methods for those
30 operations which are common to all types of sockets. Operations which
31 are specific to a particular socket domain have methods defined in
32 subclasses of "IO::Socket". See IO::Socket::INET, IO::Socket::UNIX, and
33 IO::Socket::IP for examples of such a subclass.
34
35 "IO::Socket" will export all functions (and constants) defined by
36 Socket.
37
39 Given that "IO::Socket" doesn't have attributes in the traditional
40 sense, the following arguments, rather than attributes, can be passed
41 into the constructor.
42
43 Constructor arguments should be passed in "Key => 'Value'" pairs.
44
45 The only required argument is "Domain" in IO::Socket.
46
47 Blocking
48 my $sock = IO::Socket->new(..., Blocking => 1);
49 $sock = IO::Socket->new(..., Blocking => 0);
50
51 If defined but false, the socket will be set to non-blocking mode. If
52 not specified it defaults to 1 (blocking mode).
53
54 Domain
55 my $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
56 $sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
57
58 The socket domain will define which subclass of "IO::Socket" to use.
59 The two options available along with this distribution are "AF_INET"
60 and "AF_UNIX".
61
62 "AF_INET" is for the internet address family of sockets and is handled
63 via IO::Socket::INET. "AF_INET" sockets are bound to an internet
64 address and port.
65
66 "AF_UNIX" is for the unix domain socket and is handled via
67 IO::Socket::UNIX. "AF_UNIX" sockets are bound to the file system as
68 their address name space.
69
70 This argument is required. All other arguments are optional.
71
72 Listen
73 my $sock = IO::Socket->new(..., Listen => 5);
74
75 Listen should be an integer value or left unset.
76
77 If provided, this argument will place the socket into listening mode.
78 New connections can then be accepted using the "accept" in IO::Socket
79 method. The value given is used as the listen(2) queue size.
80
81 If the "Listen" argument is given, but false, the queue size will be
82 set to 5.
83
84 Timeout
85 my $sock = IO::Socket->new(..., Timeout => 5);
86
87 The timeout value, in seconds, for this socket connection. How exactly
88 this value is utilized is defined in the socket domain subclasses that
89 make use of the value.
90
91 Type
92 my $sock = IO::Socket->new(..., Type => IO::Socket::SOCK_STREAM);
93
94 The socket type that will be used. These are usually "SOCK_STREAM",
95 "SOCK_DGRAM", or "SOCK_RAW". If this argument is left undefined an
96 attempt will be made to infer the type from the service name.
97
98 For example, you'll usually use "SOCK_STREAM" with a "tcp" connection
99 and "SOCK_DGRAM" with a "udp" connection.
100
102 "IO::Socket" extends the IO::Handle constructor.
103
104 new
105 my $sock = IO::Socket->new();
106
107 # get a new IO::Socket::INET instance
108 $sock = IO::Socket->new(Domain => IO::Socket::AF_INET);
109 # get a new IO::Socket::UNIX instance
110 $sock = IO::Socket->new(Domain => IO::Socket::AF_UNIX);
111
112 # Domain is the only required argument
113 $sock = IO::Socket->new(
114 Domain => IO::Socket::AF_INET, # AF_INET, AF_UNIX
115 Type => IO::Socket::SOCK_STREAM, # SOCK_STREAM, SOCK_DGRAM, ...
116 Proto => 'tcp', # 'tcp', 'udp', IPPROTO_TCP, IPPROTO_UDP
117 # and so on...
118 );
119
120 Creates an "IO::Socket", which is a reference to a newly created symbol
121 (see the Symbol package). "new" optionally takes arguments, these
122 arguments are defined in "CONSTRUCTOR ARGUMENTS" in IO::Socket.
123
124 Any of the "CONSTRUCTOR ARGUMENTS" in IO::Socket may be passed to the
125 constructor, but if any arguments are provided, then one of them must
126 be the "Domain" in IO::Socket argument. The "Domain" in IO::Socket
127 argument can, by default, be either "AF_INET" or "AF_UNIX". Other
128 domains can be used if a proper subclass for the domain family is
129 registered. All other arguments will be passed to the "configuration"
130 method of the package for that domain.
131
133 "IO::Socket" inherits all methods from IO::Handle and implements the
134 following new ones.
135
136 accept
137 my $client_sock = $sock->accept();
138 my $inet_sock = $sock->accept('IO::Socket::INET');
139
140 The accept method will perform the system call "accept" on the socket
141 and return a new object. The new object will be created in the same
142 class as the listen socket, unless a specific package name is
143 specified. This object can be used to communicate with the client that
144 was trying to connect.
145
146 This differs slightly from the "accept" function in perlfunc.
147
148 In a scalar context the new socket is returned, or "undef" upon
149 failure. In a list context a two-element array is returned containing
150 the new socket and the peer address; the list will be empty upon
151 failure.
152
153 atmark
154 my $integer = $sock->atmark();
155 # read in some data on a given socket
156 my $data;
157 $sock->read($data, 1024) until $sock->atmark;
158
159 # or, export the function to use:
160 use IO::Socket 'sockatmark';
161 $sock->read($data, 1024) until sockatmark($sock);
162
163 True if the socket is currently positioned at the urgent data mark,
164 false otherwise. If your system doesn't yet implement "sockatmark" this
165 will throw an exception.
166
167 If your system does not support "sockatmark", the "use" declaration
168 will fail at compile time.
169
170 autoflush
171 # by default, autoflush will be turned on when referenced
172 $sock->autoflush(); # turns on autoflush
173 # turn off autoflush
174 $sock->autoflush(0);
175 # turn on autoflush
176 $sock->autoflush(1);
177
178 This attribute isn't overridden from IO::Handle's implementation.
179 However, since we turn it on by default, it's worth mentioning here.
180
181 bind
182 use Socket qw(pack_sockaddr_in);
183 my $port = 3000;
184 my $ip_address = '0.0.0.0';
185 my $packed_addr = pack_sockaddr_in($port, $ip_address);
186 $sock->bind($packed_addr);
187
188 Binds a network address to a socket, just as bind(2) does. Returns true
189 if it succeeded, false otherwise. You should provide a packed address
190 of the appropriate type for the socket.
191
192 connected
193 my $peer_addr = $sock->connected();
194 if ($peer_addr) {
195 say "We're connected to $peer_addr";
196 }
197
198 If the socket is in a connected state, the peer address is returned. If
199 the socket is not in a connected state, "undef" is returned.
200
201 Note that this method considers a half-open TCP socket to be "in a
202 connected state". Specifically, it does not distinguish between the
203 ESTABLISHED and CLOSE-WAIT TCP states; it returns the peer address,
204 rather than "undef", in either case. Thus, in general, it cannot be
205 used to reliably learn whether the peer has initiated a graceful
206 shutdown because in most cases (see below) the local TCP state machine
207 remains in CLOSE-WAIT until the local application calls "shutdown" in
208 IO::Socket or "close". Only at that point does this function return
209 "undef".
210
211 The "in most cases" hedge is because local TCP state machine behavior
212 may depend on the peer's socket options. In particular, if the peer
213 socket has "SO_LINGER" enabled with a zero timeout, then the peer's
214 "close" will generate a "RST" segment. Upon receipt of that segment,
215 the local TCP transitions immediately to CLOSED, and in that state,
216 this method will return "undef".
217
218 getsockopt
219 my $value = $sock->getsockopt(SOL_SOCKET, SO_REUSEADDR);
220 my $buf = $socket->getsockopt(SOL_SOCKET, SO_RCVBUF);
221 say "Receive buffer is $buf bytes";
222
223 Get an option associated with the socket. Levels other than
224 "SOL_SOCKET" may be specified here. As a convenience, this method will
225 unpack a byte buffer of the correct size back into a number.
226
227 listen
228 $sock->listen(5);
229
230 Does the same thing that the listen(2) system call does. Returns true
231 if it succeeded, false otherwise. Listens to a socket with a given
232 queue size.
233
234 peername
235 my $sockaddr_in = $sock->peername();
236
237 Returns the packed "sockaddr" address of the other end of the socket
238 connection. It calls "getpeername".
239
240 protocol
241 my $proto = $sock->protocol();
242
243 Returns the number for the protocol being used on the socket, if known.
244 If the protocol is unknown, as with an "AF_UNIX" socket, zero is
245 returned.
246
247 recv
248 my $buffer = "";
249 my $length = 1024;
250 my $flags = 0; # default. optional
251 $sock->recv($buffer, $length);
252 $sock->recv($buffer, $length, $flags);
253
254 Similar in functionality to "recv" in perlfunc.
255
256 Receives a message on a socket. Attempts to receive $length characters
257 of data into $buffer from the specified socket. $buffer will be grown
258 or shrunk to the length actually read. Takes the same flags as the
259 system call of the same name. Returns the address of the sender if
260 socket's protocol supports this; returns an empty string otherwise. If
261 there's an error, returns "undef". This call is actually implemented in
262 terms of the recvfrom(2) system call.
263
264 Flags are ORed together values, such as "MSG_BCAST", "MSG_OOB",
265 "MSG_TRUNC". The default value for the flags is 0.
266
267 The cached value of "peername" in IO::Socket is updated with the result
268 of "recv".
269
270 Note: In Perl v5.30 and newer, if the socket has been marked as
271 ":utf8", "recv" will throw an exception. The ":encoding(...)" layer
272 implicitly introduces the ":utf8" layer. See "binmode" in perlfunc.
273
274 Note: In Perl versions older than v5.30, depending on the status of the
275 socket, either (8-bit) bytes or characters are received. By default all
276 sockets operate on bytes, but for example if the socket has been
277 changed using "binmode" in perlfunc to operate with the
278 ":encoding(UTF-8)" I/O layer (see the "open" in perlfunc pragma), the
279 I/O will operate on UTF8-encoded Unicode characters, not bytes.
280 Similarly for the ":encoding" layer: in that case pretty much any
281 characters can be read.
282
283 send
284 my $message = "Hello, world!";
285 my $flags = 0; # defaults to zero
286 my $to = '0.0.0.0'; # optional destination
287 my $sent = $sock->send($message);
288 $sent = $sock->send($message, $flags);
289 $sent = $sock->send($message, $flags, $to);
290
291 Similar in functionality to "send" in perlfunc.
292
293 Sends a message on a socket. Attempts to send the scalar message to the
294 socket. Takes the same flags as the system call of the same name. On
295 unconnected sockets, you must specify a destination to send to, in
296 which case it does a sendto(2) syscall. Returns the number of
297 characters sent, or "undef" on error. The sendmsg(2) syscall is
298 currently unimplemented.
299
300 The "flags" option is optional and defaults to 0.
301
302 After a successful send with $to, further calls to "send" on an
303 unconnected socket without $to will send to the same address, and $to
304 will be used as the result of "peername" in IO::Socket.
305
306 Note: In Perl v5.30 and newer, if the socket has been marked as
307 ":utf8", "send" will throw an exception. The ":encoding(...)" layer
308 implicitly introduces the ":utf8" layer. See "binmode" in perlfunc.
309
310 Note: In Perl versions older than v5.30, depending on the status of the
311 socket, either (8-bit) bytes or characters are sent. By default all
312 sockets operate on bytes, but for example if the socket has been
313 changed using "binmode" in perlfunc to operate with the
314 ":encoding(UTF-8)" I/O layer (see the "open" in perlfunc pragma), the
315 I/O will operate on UTF8-encoded Unicode characters, not bytes.
316 Similarly for the ":encoding" layer: in that case pretty much any
317 characters can be sent.
318
319 setsockopt
320 $sock->setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
321 $sock->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024);
322
323 Set option associated with the socket. Levels other than "SOL_SOCKET"
324 may be specified here. As a convenience, this method will convert a
325 number into a packed byte buffer.
326
327 shutdown
328 $sock->shutdown(SHUT_RD); # we stopped reading data
329 $sock->shutdown(SHUT_WR); # we stopped writing data
330 $sock->shutdown(SHUT_RDWR); # we stopped using this socket
331
332 Shuts down a socket connection in the manner indicated by the value
333 passed in, which has the same interpretation as in the syscall of the
334 same name.
335
336 This is useful with sockets when you want to tell the other side you're
337 done writing but not done reading, or vice versa. It's also a more
338 insistent form of "close" because it also disables the file descriptor
339 in any forked copies in other processes.
340
341 Returns 1 for success; on error, returns "undef" if the socket is not a
342 valid filehandle, or returns 0 and sets $! for any other failure.
343
344 sockdomain
345 my $domain = $sock->sockdomain();
346
347 Returns the number for the socket domain type. For example, for an
348 "AF_INET" socket the value of &AF_INET will be returned.
349
350 socket
351 my $sock = IO::Socket->new(); # no values given
352 # now let's actually get a socket with the socket method
353 # domain, type, and protocol are required
354 $sock = $sock->socket(AF_INET, SOCK_STREAM, 'tcp');
355
356 Opens a socket of the specified kind and returns it. Domain, type, and
357 protocol are specified the same as for the syscall of the same name.
358
359 socketpair
360 my ($r, $w) = $sock->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
361 ($r, $w) = IO::Socket::UNIX
362 ->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
363
364 Will return a list of two sockets created (read and write), or an empty
365 list on failure.
366
367 Differs slightly from "socketpair" in perlfunc in that the argument
368 list is a bit simpler.
369
370 sockname
371 my $packed_addr = $sock->sockname();
372
373 Returns the packed "sockaddr" address of this end of the connection.
374 It's the same as getsockname(2).
375
376 sockopt
377 my $value = $sock->sockopt(SO_REUSEADDR);
378 $sock->sockopt(SO_REUSEADDR, 1);
379
380 Unified method to both set and get options in the "SOL_SOCKET" level.
381 If called with one argument then "getsockopt" in IO::Socket is called,
382 otherwise "setsockopt" in IO::Socket is called.
383
384 socktype
385 my $type = $sock->socktype();
386
387 Returns the number for the socket type. For example, for a
388 "SOCK_STREAM" socket the value of &SOCK_STREAM will be returned.
389
390 timeout
391 my $seconds = $sock->timeout();
392 my $old_val = $sock->timeout(5); # set new and return old value
393
394 Set or get the timeout value (in seconds) associated with this socket.
395 If called without any arguments then the current setting is returned.
396 If called with an argument the current setting is changed and the
397 previous value returned.
398
399 This method is available to all "IO::Socket" implementations but may or
400 may not be used by the individual domain subclasses.
401
403 Let's create a TCP server on "localhost:3333".
404
405 use strict;
406 use warnings;
407 use feature 'say';
408
409 use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
410
411 my $server = IO::Socket->new(
412 Domain => AF_INET,
413 Type => SOCK_STREAM,
414 Proto => 'tcp',
415 LocalHost => '0.0.0.0',
416 LocalPort => 3333,
417 ReusePort => 1,
418 Listen => 5,
419 ) || die "Can't open socket: $@";
420 say "Waiting on 3333";
421
422 while (1) {
423 # waiting for a new client connection
424 my $client = $server->accept();
425
426 # get information about a newly connected client
427 my $client_address = $client->peerhost();
428 my $client_port = $client->peerport();
429 say "Connection from $client_address:$client_port";
430
431 # read up to 1024 characters from the connected client
432 my $data = "";
433 $client->recv($data, 1024);
434 say "received data: $data";
435
436 # write response data to the connected client
437 $data = "ok";
438 $client->send($data);
439
440 # notify client that response has been sent
441 $client->shutdown(SHUT_WR);
442 }
443
444 $server->close();
445
446 A client for such a server could be
447
448 use strict;
449 use warnings;
450 use feature 'say';
451
452 use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
453
454 my $client = IO::Socket->new(
455 Domain => AF_INET,
456 Type => SOCK_STREAM,
457 proto => 'tcp',
458 PeerPort => 3333,
459 PeerHost => '0.0.0.0',
460 ) || die "Can't open socket: $@";
461
462 say "Sending Hello World!";
463 my $size = $client->send("Hello World!");
464 say "Sent data of length: $size";
465
466 $client->shutdown(SHUT_WR);
467
468 my $buffer;
469 $client->recv($buffer, 1024);
470 say "Got back $buffer";
471
472 $client->close();
473
475 On some systems, for an IO::Socket object created with "new_from_fd",
476 or created with "accept" in IO::Socket from such an object, the
477 "protocol" in IO::Socket, "sockdomain" in IO::Socket and "socktype" in
478 IO::Socket methods may return "undef".
479
481 Socket, IO::Handle, IO::Socket::INET, IO::Socket::UNIX, IO::Socket::IP
482
484 Graham Barr. atmark() by Lincoln Stein. Currently maintained by the
485 Perl Porters. Please report all bugs to <perlbug@perl.org>.
486
488 Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights
489 reserved. This program is free software; you can redistribute it
490 and/or modify it under the same terms as Perl itself.
491
492 The atmark() implementation: Copyright 2001, Lincoln Stein
493 <lstein@cshl.org>. This module is distributed under the same terms as
494 Perl itself. Feel free to use, modify and redistribute it as long as
495 you retain the correct attribution.
496
497
498
499perl v5.32.1 2021-05-31 IO::Socket(3pm)