1Socket(3) User Contributed Perl Documentation Socket(3)
2
3
4
6 "Socket" - networking constants and support functions
7
9 "Socket" a low-level module used by, among other things, the IO::Socket
10 family of modules. The following examples demonstrate some low-level
11 uses but a practical program would likely use the higher-level API
12 provided by "IO::Socket" or similar instead.
13
14 use Socket qw(PF_INET SOCK_STREAM pack_sockaddr_in inet_aton);
15
16 socket(my $socket, PF_INET, SOCK_STREAM, 0)
17 or die "socket: $!";
18
19 my $port = getservbyname "echo", "tcp";
20 connect($socket, pack_sockaddr_in($port, inet_aton("localhost")))
21 or die "connect: $!";
22
23 print $socket "Hello, world!\n";
24 print <$socket>;
25
26 See also the "EXAMPLES" section.
27
29 This module provides a variety of constants, structure manipulators and
30 other functions related to socket-based networking. The values and
31 functions provided are useful when used in conjunction with Perl core
32 functions such as socket(), setsockopt() and bind(). It also provides
33 several other support functions, mostly for dealing with conversions of
34 network addresses between human-readable and native binary forms, and
35 for hostname resolver operations.
36
37 Some constants and functions are exported by default by this module;
38 but for backward-compatibility any recently-added symbols are not
39 exported by default and must be requested explicitly. When an import
40 list is provided to the "use Socket" line, the default exports are not
41 automatically imported. It is therefore best practice to always to
42 explicitly list all the symbols required.
43
44 Also, some common socket "newline" constants are provided: the
45 constants "CR", "LF", and "CRLF", as well as $CR, $LF, and $CRLF, which
46 map to "\015", "\012", and "\015\012". If you do not want to use the
47 literal characters in your programs, then use the constants provided
48 here. They are not exported by default, but can be imported
49 individually, and with the ":crlf" export tag:
50
51 use Socket qw(:DEFAULT :crlf);
52
53 $sock->print("GET / HTTP/1.0$CRLF");
54
55 The entire getaddrinfo() subsystem can be exported using the tag
56 ":addrinfo"; this exports the getaddrinfo() and getnameinfo()
57 functions, and all the "AI_*", "NI_*", "NIx_*" and "EAI_*" constants.
58
60 In each of the following groups, there may be many more constants
61 provided than just the ones given as examples in the section heading.
62 If the heading ends "..." then this means there are likely more; the
63 exact constants provided will depend on the OS and headers found at
64 compile-time.
65
66 PF_INET, PF_INET6, PF_UNIX, ...
67 Protocol family constants to use as the first argument to socket() or
68 the value of the "SO_DOMAIN" or "SO_FAMILY" socket option.
69
70 AF_INET, AF_INET6, AF_UNIX, ...
71 Address family constants used by the socket address structures, to pass
72 to such functions as inet_pton() or getaddrinfo(), or are returned by
73 such functions as sockaddr_family().
74
75 SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ...
76 Socket type constants to use as the second argument to socket(), or the
77 value of the "SO_TYPE" socket option.
78
79 SOCK_NONBLOCK. SOCK_CLOEXEC
80 Linux-specific shortcuts to specify the "O_NONBLOCK" and "FD_CLOEXEC"
81 flags during a socket(2) call.
82
83 socket( my $sockh, PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0 )
84
85 SOL_SOCKET
86 Socket option level constant for setsockopt() and getsockopt().
87
88 SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ...
89 Socket option name constants for setsockopt() and getsockopt() at the
90 "SOL_SOCKET" level.
91
92 IP_OPTIONS, IP_TOS, IP_TTL, ...
93 Socket option name constants for IPv4 socket options at the
94 "IPPROTO_IP" level.
95
96 IP_PMTUDISC_WANT, IP_PMTUDISC_DONT, ...
97 Socket option value constants for "IP_MTU_DISCOVER" socket option.
98
99 IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ...
100 Socket option value constants for "IP_TOS" socket option.
101
102 MSG_BCAST, MSG_OOB, MSG_TRUNC, ...
103 Message flag constants for send() and recv().
104
105 SHUT_RD, SHUT_RDWR, SHUT_WR
106 Direction constants for shutdown().
107
108 INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE
109 Constants giving the special "AF_INET" addresses for wildcard,
110 broadcast, local loopback, and invalid addresses.
111
112 Normally equivalent to inet_aton('0.0.0.0'),
113 inet_aton('255.255.255.255'), inet_aton('localhost') and
114 inet_aton('255.255.255.255') respectively.
115
116 IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ...
117 IP protocol constants to use as the third argument to socket(), the
118 level argument to getsockopt() or setsockopt(), or the value of the
119 "SO_PROTOCOL" socket option.
120
121 TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ...
122 Socket option name constants for TCP socket options at the
123 "IPPROTO_TCP" level.
124
125 IN6ADDR_ANY, IN6ADDR_LOOPBACK
126 Constants giving the special "AF_INET6" addresses for wildcard and
127 local loopback.
128
129 Normally equivalent to inet_pton(AF_INET6, "::") and
130 inet_pton(AF_INET6, "::1") respectively.
131
132 IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ...
133 Socket option name constants for IPv6 socket options at the
134 "IPPROTO_IPV6" level.
135
137 The following functions convert between lists of Perl values and packed
138 binary strings representing structures.
139
140 $family = sockaddr_family $sockaddr
141 Takes a packed socket address (as returned by pack_sockaddr_in(),
142 pack_sockaddr_un() or the perl builtin functions getsockname() and
143 getpeername()). Returns the address family tag. This will be one of the
144 "AF_*" constants, such as "AF_INET" for a "sockaddr_in" addresses or
145 "AF_UNIX" for a "sockaddr_un". It can be used to figure out what unpack
146 to use for a sockaddr of unknown type.
147
148 $sockaddr = pack_sockaddr_in $port, $ip_address
149 Takes two arguments, a port number and an opaque string (as returned by
150 inet_aton(), or a v-string). Returns the "sockaddr_in" structure with
151 those arguments packed in and "AF_INET" filled in. For Internet domain
152 sockets, this structure is normally what you need for the arguments in
153 bind(), connect(), and send().
154
155 An undefined $port argument is taken as zero; an undefined $ip_address
156 is considered a fatal error.
157
158 ($port, $ip_address) = unpack_sockaddr_in $sockaddr
159 Takes a "sockaddr_in" structure (as returned by pack_sockaddr_in(),
160 getpeername() or recv()). Returns a list of two elements: the port and
161 an opaque string representing the IP address (you can use inet_ntoa()
162 to convert the address to the four-dotted numeric format). Will croak
163 if the structure does not represent an "AF_INET" address.
164
165 In scalar context will return just the IP address.
166
167 $sockaddr = sockaddr_in $port, $ip_address
168 ($port, $ip_address) = sockaddr_in $sockaddr
169 A wrapper of pack_sockaddr_in() or unpack_sockaddr_in(). In list
170 context, unpacks its argument and returns a list consisting of the port
171 and IP address. In scalar context, packs its port and IP address
172 arguments as a "sockaddr_in" and returns it.
173
174 Provided largely for legacy compatibility; it is better to use
175 pack_sockaddr_in() or unpack_sockaddr_in() explicitly.
176
177 $sockaddr = pack_sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]]
178 Takes two to four arguments, a port number, an opaque string (as
179 returned by inet_pton()), optionally a scope ID number, and optionally
180 a flow label number. Returns the "sockaddr_in6" structure with those
181 arguments packed in and "AF_INET6" filled in. IPv6 equivalent of
182 pack_sockaddr_in().
183
184 An undefined $port argument is taken as zero; an undefined $ip6_address
185 is considered a fatal error.
186
187 ($port, $ip6_address, $scope_id, $flowinfo) = unpack_sockaddr_in6 $sockaddr
188 Takes a "sockaddr_in6" structure. Returns a list of four elements: the
189 port number, an opaque string representing the IPv6 address, the scope
190 ID, and the flow label. (You can use inet_ntop() to convert the address
191 to the usual string format). Will croak if the structure does not
192 represent an "AF_INET6" address.
193
194 In scalar context will return just the IP address.
195
196 $sockaddr = sockaddr_in6 $port, $ip6_address, [$scope_id, [$flowinfo]]
197 ($port, $ip6_address, $scope_id, $flowinfo) = sockaddr_in6 $sockaddr
198 A wrapper of pack_sockaddr_in6() or unpack_sockaddr_in6(). In list
199 context, unpacks its argument according to unpack_sockaddr_in6(). In
200 scalar context, packs its arguments according to pack_sockaddr_in6().
201
202 Provided largely for legacy compatibility; it is better to use
203 pack_sockaddr_in6() or unpack_sockaddr_in6() explicitly.
204
205 $sockaddr = pack_sockaddr_un $path
206 Takes one argument, a pathname. Returns the "sockaddr_un" structure
207 with that path packed in with "AF_UNIX" filled in. For "PF_UNIX"
208 sockets, this structure is normally what you need for the arguments in
209 bind(), connect(), and send().
210
211 ($path) = unpack_sockaddr_un $sockaddr
212 Takes a "sockaddr_un" structure (as returned by pack_sockaddr_un(),
213 getpeername() or recv()). Returns a list of one element: the pathname.
214 Will croak if the structure does not represent an "AF_UNIX" address.
215
216 $sockaddr = sockaddr_un $path
217 ($path) = sockaddr_un $sockaddr
218 A wrapper of pack_sockaddr_un() or unpack_sockaddr_un(). In a list
219 context, unpacks its argument and returns a list consisting of the
220 pathname. In a scalar context, packs its pathname as a "sockaddr_un"
221 and returns it.
222
223 Provided largely for legacy compatibility; it is better to use
224 pack_sockaddr_un() or unpack_sockaddr_un() explicitly.
225
226 These are only supported if your system has <sys/un.h>.
227
228 $ip_mreq = pack_ip_mreq $multiaddr, $interface
229 Takes an IPv4 multicast address and optionally an interface address (or
230 "INADDR_ANY"). Returns the "ip_mreq" structure with those arguments
231 packed in. Suitable for use with the "IP_ADD_MEMBERSHIP" and
232 "IP_DROP_MEMBERSHIP" sockopts.
233
234 ($multiaddr, $interface) = unpack_ip_mreq $ip_mreq
235 Takes an "ip_mreq" structure. Returns a list of two elements; the IPv4
236 multicast address and interface address.
237
238 $ip_mreq_source = pack_ip_mreq_source $multiaddr, $source, $interface
239 Takes an IPv4 multicast address, source address, and optionally an
240 interface address (or "INADDR_ANY"). Returns the "ip_mreq_source"
241 structure with those arguments packed in. Suitable for use with the
242 "IP_ADD_SOURCE_MEMBERSHIP" and "IP_DROP_SOURCE_MEMBERSHIP" sockopts.
243
244 ($multiaddr, $source, $interface) = unpack_ip_mreq_source $ip_mreq
245 Takes an "ip_mreq_source" structure. Returns a list of three elements;
246 the IPv4 multicast address, source address and interface address.
247
248 $ipv6_mreq = pack_ipv6_mreq $multiaddr6, $ifindex
249 Takes an IPv6 multicast address and an interface number. Returns the
250 "ipv6_mreq" structure with those arguments packed in. Suitable for use
251 with the "IPV6_ADD_MEMBERSHIP" and "IPV6_DROP_MEMBERSHIP" sockopts.
252
253 ($multiaddr6, $ifindex) = unpack_ipv6_mreq $ipv6_mreq
254 Takes an "ipv6_mreq" structure. Returns a list of two elements; the
255 IPv6 address and an interface number.
256
258 $ip_address = inet_aton $string
259 Takes a string giving the name of a host, or a textual representation
260 of an IP address and translates that to an packed binary address
261 structure suitable to pass to pack_sockaddr_in(). If passed a hostname
262 that cannot be resolved, returns "undef". For multi-homed hosts (hosts
263 with more than one address), the first address found is returned.
264
265 For portability do not assume that the result of inet_aton() is 32 bits
266 wide, in other words, that it would contain only the IPv4 address in
267 network order.
268
269 This IPv4-only function is provided largely for legacy reasons. Newly-
270 written code should use getaddrinfo() or inet_pton() instead for IPv6
271 support.
272
273 $string = inet_ntoa $ip_address
274 Takes a packed binary address structure such as returned by
275 unpack_sockaddr_in() (or a v-string representing the four octets of the
276 IPv4 address in network order) and translates it into a string of the
277 form "d.d.d.d" where the "d"s are numbers less than 256 (the normal
278 human-readable four dotted number notation for Internet addresses).
279
280 This IPv4-only function is provided largely for legacy reasons. Newly-
281 written code should use getnameinfo() or inet_ntop() instead for IPv6
282 support.
283
284 $address = inet_pton $family, $string
285 Takes an address family (such as "AF_INET" or "AF_INET6") and a string
286 containing a textual representation of an address in that family and
287 translates that to an packed binary address structure.
288
289 See also getaddrinfo() for a more powerful and flexible function to
290 look up socket addresses given hostnames or textual addresses.
291
292 $string = inet_ntop $family, $address
293 Takes an address family and a packed binary address structure and
294 translates it into a human-readable textual representation of the
295 address; typically in "d.d.d.d" form for "AF_INET" or "hhhh:hhhh::hhhh"
296 form for "AF_INET6".
297
298 See also getnameinfo() for a more powerful and flexible function to
299 turn socket addresses into human-readable textual representations.
300
301 ($err, @result) = getaddrinfo $host, $service, [$hints]
302 Given both a hostname and service name, this function attempts to
303 resolve the host name into a list of network addresses, and the service
304 name into a protocol and port number, and then returns a list of
305 address structures suitable to connect() to it.
306
307 Given just a host name, this function attempts to resolve it to a list
308 of network addresses, and then returns a list of address structures
309 giving these addresses.
310
311 Given just a service name, this function attempts to resolve it to a
312 protocol and port number, and then returns a list of address structures
313 that represent it suitable to bind() to. This use should be combined
314 with the "AI_PASSIVE" flag; see below.
315
316 Given neither name, it generates an error.
317
318 If present, $hints should be a reference to a hash, where the following
319 keys are recognised:
320
321 flags => INT
322 A bitfield containing "AI_*" constants; see below.
323
324 family => INT
325 Restrict to only generating addresses in this address family
326
327 socktype => INT
328 Restrict to only generating addresses of this socket type
329
330 protocol => INT
331 Restrict to only generating addresses for this protocol
332
333 The return value will be a list; the first value being an error
334 indication, followed by a list of address structures (if no error
335 occurred).
336
337 The error value will be a dualvar; comparable to the "EAI_*" error
338 constants, or printable as a human-readable error message string. If no
339 error occurred it will be zero numerically and an empty string.
340
341 Each value in the results list will be a hash reference containing the
342 following fields:
343
344 family => INT
345 The address family (e.g. "AF_INET")
346
347 socktype => INT
348 The socket type (e.g. "SOCK_STREAM")
349
350 protocol => INT
351 The protocol (e.g. "IPPROTO_TCP")
352
353 addr => STRING
354 The address in a packed string (such as would be returned by
355 pack_sockaddr_in())
356
357 canonname => STRING
358 The canonical name for the host if the "AI_CANONNAME" flag was
359 provided, or "undef" otherwise. This field will only be present on
360 the first returned address.
361
362 The following flag constants are recognised in the $hints hash. Other
363 flag constants may exist as provided by the OS.
364
365 AI_PASSIVE
366 Indicates that this resolution is for a local bind() for a passive
367 (i.e. listening) socket, rather than an active (i.e. connecting)
368 socket.
369
370 AI_CANONNAME
371 Indicates that the caller wishes the canonical hostname
372 ("canonname") field of the result to be filled in.
373
374 AI_NUMERICHOST
375 Indicates that the caller will pass a numeric address, rather than
376 a hostname, and that getaddrinfo() must not perform a resolve
377 operation on this name. This flag will prevent a possibly-slow
378 network lookup operation, and instead return an error if a hostname
379 is passed.
380
381 ($err, $hostname, $servicename) = getnameinfo $sockaddr, [$flags,
382 [$xflags]]
383 Given a packed socket address (such as from getsockname(),
384 getpeername(), or returned by getaddrinfo() in a "addr" field), returns
385 the hostname and symbolic service name it represents. $flags may be a
386 bitmask of "NI_*" constants, or defaults to 0 if unspecified.
387
388 The return value will be a list; the first value being an error
389 condition, followed by the hostname and service name.
390
391 The error value will be a dualvar; comparable to the "EAI_*" error
392 constants, or printable as a human-readable error message string. The
393 host and service names will be plain strings.
394
395 The following flag constants are recognised as $flags. Other flag
396 constants may exist as provided by the OS.
397
398 NI_NUMERICHOST
399 Requests that a human-readable string representation of the numeric
400 address be returned directly, rather than performing a name resolve
401 operation that may convert it into a hostname. This will also avoid
402 potentially-blocking network IO.
403
404 NI_NUMERICSERV
405 Requests that the port number be returned directly as a number
406 representation rather than performing a name resolve operation that
407 may convert it into a service name.
408
409 NI_NAMEREQD
410 If a name resolve operation fails to provide a name, then this flag
411 will cause getnameinfo() to indicate an error, rather than
412 returning the numeric representation as a human-readable string.
413
414 NI_DGRAM
415 Indicates that the socket address relates to a "SOCK_DGRAM" socket,
416 for the services whose name differs between TCP and UDP protocols.
417
418 The following constants may be supplied as $xflags.
419
420 NIx_NOHOST
421 Indicates that the caller is not interested in the hostname of the
422 result, so it does not have to be converted. "undef" will be
423 returned as the hostname.
424
425 NIx_NOSERV
426 Indicates that the caller is not interested in the service name of
427 the result, so it does not have to be converted. "undef" will be
428 returned as the service name.
429
431 The following constants may be returned by getaddrinfo() or
432 getnameinfo(). Others may be provided by the OS.
433
434 EAI_AGAIN
435 A temporary failure occurred during name resolution. The operation
436 may be successful if it is retried later.
437
438 EAI_BADFLAGS
439 The value of the "flags" hint to getaddrinfo(), or the $flags
440 parameter to getnameinfo() contains unrecognised flags.
441
442 EAI_FAMILY
443 The "family" hint to getaddrinfo(), or the family of the socket
444 address passed to getnameinfo() is not supported.
445
446 EAI_NODATA
447 The host name supplied to getaddrinfo() did not provide any usable
448 address data.
449
450 EAI_NONAME
451 The host name supplied to getaddrinfo() does not exist, or the
452 address supplied to getnameinfo() is not associated with a host
453 name and the "NI_NAMEREQD" flag was supplied.
454
455 EAI_SERVICE
456 The service name supplied to getaddrinfo() is not available for the
457 socket type given in the $hints.
458
460 Lookup for connect()
461 The getaddrinfo() function converts a hostname and a service name into
462 a list of structures, each containing a potential way to connect() to
463 the named service on the named host.
464
465 use IO::Socket;
466 use Socket qw(SOCK_STREAM getaddrinfo);
467
468 my %hints = (socktype => SOCK_STREAM);
469 my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
470 die "Cannot getaddrinfo - $err" if $err;
471
472 my $sock;
473
474 foreach my $ai (@res) {
475 my $candidate = IO::Socket->new();
476
477 $candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
478 or next;
479
480 $candidate->connect($ai->{addr})
481 or next;
482
483 $sock = $candidate;
484 last;
485 }
486
487 die "Cannot connect to localhost:echo" unless $sock;
488
489 $sock->print("Hello, world!\n");
490 print <$sock>;
491
492 Because a list of potential candidates is returned, the "while" loop
493 tries each in turn until it finds one that succeeds both the socket()
494 and connect() calls.
495
496 This function performs the work of the legacy functions
497 gethostbyname(), getservbyname(), inet_aton() and pack_sockaddr_in().
498
499 In practice this logic is better performed by IO::Socket::IP.
500
501 Making a human-readable string out of an address
502 The getnameinfo() function converts a socket address, such as returned
503 by getsockname() or getpeername(), into a pair of human-readable
504 strings representing the address and service name.
505
506 use IO::Socket::IP;
507 use Socket qw(getnameinfo);
508
509 my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
510 die "Cannot listen - $@";
511
512 my $socket = $server->accept or die "accept: $!";
513
514 my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
515 die "Cannot getnameinfo - $err" if $err;
516
517 print "The peer is connected from $hostname\n";
518
519 Since in this example only the hostname was used, the redundant
520 conversion of the port number into a service name may be omitted by
521 passing the "NIx_NOSERV" flag.
522
523 use Socket qw(getnameinfo NIx_NOSERV);
524
525 my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);
526
527 This function performs the work of the legacy functions
528 unpack_sockaddr_in(), inet_ntoa(), gethostbyaddr() and getservbyport().
529
530 In practice this logic is better performed by IO::Socket::IP.
531
532 Resolving hostnames into IP addresses
533 To turn a hostname into a human-readable plain IP address use
534 getaddrinfo() to turn the hostname into a list of socket structures,
535 then getnameinfo() on each one to make it a readable IP address again.
536
537 use Socket qw(:addrinfo SOCK_RAW);
538
539 my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
540 die "Cannot getaddrinfo - $err" if $err;
541
542 while( my $ai = shift @res ) {
543 my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
544 die "Cannot getnameinfo - $err" if $err;
545
546 print "$ipaddr\n";
547 }
548
549 The "socktype" hint to getaddrinfo() filters the results to only
550 include one socket type and protocol. Without this most OSes return
551 three combinations, for "SOCK_STREAM", "SOCK_DGRAM" and "SOCK_RAW",
552 resulting in triplicate output of addresses. The "NI_NUMERICHOST" flag
553 to getnameinfo() causes it to return a string-formatted plain IP
554 address, rather than reverse resolving it back into a hostname.
555
556 This combination performs the work of the legacy functions
557 gethostbyname() and inet_ntoa().
558
559 Accessing socket options
560 The many "SO_*" and other constants provide the socket option names for
561 getsockopt() and setsockopt().
562
563 use IO::Socket::INET;
564 use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);
565
566 my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
567 or die "Cannot create socket: $@";
568
569 $socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
570 die "setsockopt: $!";
571
572 print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
573 " bytes\n";
574
575 print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";
576
577 As a convenience, IO::Socket's setsockopt() method will convert a
578 number into a packed byte buffer, and getsockopt() will unpack a byte
579 buffer of the correct size back into a number.
580
582 This module was originally maintained in Perl core by the Perl 5
583 Porters.
584
585 It was extracted to dual-life on CPAN at version 1.95 by Paul Evans
586 <leonerd@leonerd.org.uk>
587
588
589
590perl v5.34.1 2022-07-11 Socket(3)