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