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
132 If the constructor fails it will return "undef" and set the $errstr
133 package variable to contain an error message.
134
135 $sock = IO::Socket->new(...)
136 or die "Cannot create socket - $IO::Socket::errstr\n";
137
138 For legacy reasons the error message is also set into the global $@
139 variable, and you may still find older code which looks here instead.
140
141 $sock = IO::Socket->new(...)
142 or die "Cannot create socket - $@\n";
143
145 "IO::Socket" inherits all methods from IO::Handle and implements the
146 following new ones.
147
148 accept
149 my $client_sock = $sock->accept();
150 my $inet_sock = $sock->accept('IO::Socket::INET');
151
152 The accept method will perform the system call "accept" on the socket
153 and return a new object. The new object will be created in the same
154 class as the listen socket, unless a specific package name is
155 specified. This object can be used to communicate with the client that
156 was trying to connect.
157
158 This differs slightly from the "accept" function in perlfunc.
159
160 In a scalar context the new socket is returned, or "undef" upon
161 failure. In a list context a two-element array is returned containing
162 the new socket and the peer address; the list will be empty upon
163 failure.
164
165 atmark
166 my $integer = $sock->atmark();
167 # read in some data on a given socket
168 my $data;
169 $sock->read($data, 1024) until $sock->atmark;
170
171 # or, export the function to use:
172 use IO::Socket 'sockatmark';
173 $sock->read($data, 1024) until sockatmark($sock);
174
175 True if the socket is currently positioned at the urgent data mark,
176 false otherwise. If your system doesn't yet implement "sockatmark" this
177 will throw an exception.
178
179 If your system does not support "sockatmark", the "use" declaration
180 will fail at compile time.
181
182 autoflush
183 # by default, autoflush will be turned on when referenced
184 $sock->autoflush(); # turns on autoflush
185 # turn off autoflush
186 $sock->autoflush(0);
187 # turn on autoflush
188 $sock->autoflush(1);
189
190 This attribute isn't overridden from IO::Handle's implementation.
191 However, since we turn it on by default, it's worth mentioning here.
192
193 bind
194 use Socket qw(pack_sockaddr_in);
195 my $port = 3000;
196 my $ip_address = '0.0.0.0';
197 my $packed_addr = pack_sockaddr_in($port, $ip_address);
198 $sock->bind($packed_addr);
199
200 Binds a network address to a socket, just as bind(2) does. Returns true
201 if it succeeded, false otherwise. You should provide a packed address
202 of the appropriate type for the socket.
203
204 connected
205 my $peer_addr = $sock->connected();
206 if ($peer_addr) {
207 say "We're connected to $peer_addr";
208 }
209
210 If the socket is in a connected state, the peer address is returned. If
211 the socket is not in a connected state, "undef" is returned.
212
213 Note that this method considers a half-open TCP socket to be "in a
214 connected state". Specifically, it does not distinguish between the
215 ESTABLISHED and CLOSE-WAIT TCP states; it returns the peer address,
216 rather than "undef", in either case. Thus, in general, it cannot be
217 used to reliably learn whether the peer has initiated a graceful
218 shutdown because in most cases (see below) the local TCP state machine
219 remains in CLOSE-WAIT until the local application calls "shutdown" in
220 IO::Socket or "close". Only at that point does this function return
221 "undef".
222
223 The "in most cases" hedge is because local TCP state machine behavior
224 may depend on the peer's socket options. In particular, if the peer
225 socket has "SO_LINGER" enabled with a zero timeout, then the peer's
226 "close" will generate a "RST" segment. Upon receipt of that segment,
227 the local TCP transitions immediately to CLOSED, and in that state,
228 this method will return "undef".
229
230 getsockopt
231 my $value = $sock->getsockopt(SOL_SOCKET, SO_REUSEADDR);
232 my $buf = $socket->getsockopt(SOL_SOCKET, SO_RCVBUF);
233 say "Receive buffer is $buf bytes";
234
235 Get an option associated with the socket. Levels other than
236 "SOL_SOCKET" may be specified here. As a convenience, this method will
237 unpack a byte buffer of the correct size back into a number.
238
239 listen
240 $sock->listen(5);
241
242 Does the same thing that the listen(2) system call does. Returns true
243 if it succeeded, false otherwise. Listens to a socket with a given
244 queue size.
245
246 peername
247 my $sockaddr_in = $sock->peername();
248
249 Returns the packed "sockaddr" address of the other end of the socket
250 connection. It calls "getpeername".
251
252 protocol
253 my $proto = $sock->protocol();
254
255 Returns the number for the protocol being used on the socket, if known.
256 If the protocol is unknown, as with an "AF_UNIX" socket, zero is
257 returned.
258
259 recv
260 my $buffer = "";
261 my $length = 1024;
262 my $flags = 0; # default. optional
263 $sock->recv($buffer, $length);
264 $sock->recv($buffer, $length, $flags);
265
266 Similar in functionality to "recv" in perlfunc.
267
268 Receives a message on a socket. Attempts to receive $length characters
269 of data into $buffer from the specified socket. $buffer will be grown
270 or shrunk to the length actually read. Takes the same flags as the
271 system call of the same name. Returns the address of the sender if
272 socket's protocol supports this; returns an empty string otherwise. If
273 there's an error, returns "undef". This call is actually implemented in
274 terms of the recvfrom(2) system call.
275
276 Flags are ORed together values, such as "MSG_BCAST", "MSG_OOB",
277 "MSG_TRUNC". The default value for the flags is 0.
278
279 The cached value of "peername" in IO::Socket is updated with the result
280 of "recv".
281
282 Note: In Perl v5.30 and newer, if the socket has been marked as
283 ":utf8", "recv" will throw an exception. The ":encoding(...)" layer
284 implicitly introduces the ":utf8" layer. See "binmode" in perlfunc.
285
286 Note: In Perl versions older than v5.30, depending on the status of the
287 socket, either (8-bit) bytes or characters are received. By default all
288 sockets operate on bytes, but for example if the socket has been
289 changed using "binmode" in perlfunc to operate with the
290 ":encoding(UTF-8)" I/O layer (see the "open" in perlfunc pragma), the
291 I/O will operate on UTF8-encoded Unicode characters, not bytes.
292 Similarly for the ":encoding" layer: in that case pretty much any
293 characters can be read.
294
295 send
296 my $message = "Hello, world!";
297 my $flags = 0; # defaults to zero
298 my $to = '0.0.0.0'; # optional destination
299 my $sent = $sock->send($message);
300 $sent = $sock->send($message, $flags);
301 $sent = $sock->send($message, $flags, $to);
302
303 Similar in functionality to "send" in perlfunc.
304
305 Sends a message on a socket. Attempts to send the scalar message to the
306 socket. Takes the same flags as the system call of the same name. On
307 unconnected sockets, you must specify a destination to send to, in
308 which case it does a sendto(2) syscall. Returns the number of
309 characters sent, or "undef" on error. The sendmsg(2) syscall is
310 currently unimplemented.
311
312 The "flags" option is optional and defaults to 0.
313
314 After a successful send with $to, further calls to "send" on an
315 unconnected socket without $to will send to the same address, and $to
316 will be used as the result of "peername" in IO::Socket.
317
318 Note: In Perl v5.30 and newer, if the socket has been marked as
319 ":utf8", "send" will throw an exception. The ":encoding(...)" layer
320 implicitly introduces the ":utf8" layer. See "binmode" in perlfunc.
321
322 Note: In Perl versions older than v5.30, depending on the status of the
323 socket, either (8-bit) bytes or characters are sent. By default all
324 sockets operate on bytes, but for example if the socket has been
325 changed using "binmode" in perlfunc to operate with the
326 ":encoding(UTF-8)" I/O layer (see the "open" in perlfunc pragma), the
327 I/O will operate on UTF8-encoded Unicode characters, not bytes.
328 Similarly for the ":encoding" layer: in that case pretty much any
329 characters can be sent.
330
331 setsockopt
332 $sock->setsockopt(SOL_SOCKET, SO_REUSEADDR, 1);
333 $sock->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024);
334
335 Set option associated with the socket. Levels other than "SOL_SOCKET"
336 may be specified here. As a convenience, this method will convert a
337 number into a packed byte buffer.
338
339 shutdown
340 $sock->shutdown(SHUT_RD); # we stopped reading data
341 $sock->shutdown(SHUT_WR); # we stopped writing data
342 $sock->shutdown(SHUT_RDWR); # we stopped using this socket
343
344 Shuts down a socket connection in the manner indicated by the value
345 passed in, which has the same interpretation as in the syscall of the
346 same name.
347
348 This is useful with sockets when you want to tell the other side you're
349 done writing but not done reading, or vice versa. It's also a more
350 insistent form of "close" because it also disables the file descriptor
351 in any forked copies in other processes.
352
353 Returns 1 for success; on error, returns "undef" if the socket is not a
354 valid filehandle, or returns 0 and sets $! for any other failure.
355
356 sockdomain
357 my $domain = $sock->sockdomain();
358
359 Returns the number for the socket domain type. For example, for an
360 "AF_INET" socket the value of &AF_INET will be returned.
361
362 socket
363 my $sock = IO::Socket->new(); # no values given
364 # now let's actually get a socket with the socket method
365 # domain, type, and protocol are required
366 $sock = $sock->socket(AF_INET, SOCK_STREAM, 'tcp');
367
368 Opens a socket of the specified kind and returns it. Domain, type, and
369 protocol are specified the same as for the syscall of the same name.
370
371 socketpair
372 my ($r, $w) = $sock->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
373 ($r, $w) = IO::Socket::UNIX
374 ->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
375
376 Will return a list of two sockets created (read and write), or an empty
377 list on failure.
378
379 Differs slightly from "socketpair" in perlfunc in that the argument
380 list is a bit simpler.
381
382 sockname
383 my $packed_addr = $sock->sockname();
384
385 Returns the packed "sockaddr" address of this end of the connection.
386 It's the same as getsockname(2).
387
388 sockopt
389 my $value = $sock->sockopt(SO_REUSEADDR);
390 $sock->sockopt(SO_REUSEADDR, 1);
391
392 Unified method to both set and get options in the "SOL_SOCKET" level.
393 If called with one argument then "getsockopt" in IO::Socket is called,
394 otherwise "setsockopt" in IO::Socket is called.
395
396 socktype
397 my $type = $sock->socktype();
398
399 Returns the number for the socket type. For example, for a
400 "SOCK_STREAM" socket the value of &SOCK_STREAM will be returned.
401
402 timeout
403 my $seconds = $sock->timeout();
404 my $old_val = $sock->timeout(5); # set new and return old value
405
406 Set or get the timeout value (in seconds) associated with this socket.
407 If called without any arguments then the current setting is returned.
408 If called with an argument the current setting is changed and the
409 previous value returned.
410
411 This method is available to all "IO::Socket" implementations but may or
412 may not be used by the individual domain subclasses.
413
415 Let's create a TCP server on "localhost:3333".
416
417 use strict;
418 use warnings;
419 use feature 'say';
420
421 use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
422
423 my $server = IO::Socket->new(
424 Domain => AF_INET,
425 Type => SOCK_STREAM,
426 Proto => 'tcp',
427 LocalHost => '0.0.0.0',
428 LocalPort => 3333,
429 ReusePort => 1,
430 Listen => 5,
431 ) || die "Can't open socket: $IO::Socket::errstr";
432 say "Waiting on 3333";
433
434 while (1) {
435 # waiting for a new client connection
436 my $client = $server->accept();
437
438 # get information about a newly connected client
439 my $client_address = $client->peerhost();
440 my $client_port = $client->peerport();
441 say "Connection from $client_address:$client_port";
442
443 # read up to 1024 characters from the connected client
444 my $data = "";
445 $client->recv($data, 1024);
446 say "received data: $data";
447
448 # write response data to the connected client
449 $data = "ok";
450 $client->send($data);
451
452 # notify client that response has been sent
453 $client->shutdown(SHUT_WR);
454 }
455
456 $server->close();
457
458 A client for such a server could be
459
460 use strict;
461 use warnings;
462 use feature 'say';
463
464 use IO::Socket qw(AF_INET AF_UNIX SOCK_STREAM SHUT_WR);
465
466 my $client = IO::Socket->new(
467 Domain => AF_INET,
468 Type => SOCK_STREAM,
469 proto => 'tcp',
470 PeerPort => 3333,
471 PeerHost => '0.0.0.0',
472 ) || die "Can't open socket: $IO::Socket::errstr";
473
474 say "Sending Hello World!";
475 my $size = $client->send("Hello World!");
476 say "Sent data of length: $size";
477
478 $client->shutdown(SHUT_WR);
479
480 my $buffer;
481 $client->recv($buffer, 1024);
482 say "Got back $buffer";
483
484 $client->close();
485
487 On some systems, for an IO::Socket object created with "new_from_fd",
488 or created with "accept" in IO::Socket from such an object, the
489 "protocol" in IO::Socket, "sockdomain" in IO::Socket and "socktype" in
490 IO::Socket methods may return "undef".
491
493 Socket, IO::Handle, IO::Socket::INET, IO::Socket::UNIX, IO::Socket::IP
494
496 Graham Barr. atmark() by Lincoln Stein. Currently maintained by the
497 Perl 5 Porters. Please report all bugs at
498 <https://github.com/Perl/perl5/issues>.
499
501 Copyright (c) 1997-8 Graham Barr <gbarr@pobox.com>. All rights
502 reserved. This program is free software; you can redistribute it
503 and/or modify it under the same terms as Perl itself.
504
505 The atmark() implementation: Copyright 2001, Lincoln Stein
506 <lstein@cshl.org>. This module is distributed under the same terms as
507 Perl itself. Feel free to use, modify and redistribute it as long as
508 you retain the correct attribution.
509
510
511
512perl v5.36.0 2022-08-30 IO::Socket(3pm)