1AnyEvent::Socket(3)   User Contributed Perl Documentation  AnyEvent::Socket(3)
2
3
4

NAME

6       AnyEvent::Socket - useful IPv4 and IPv6 stuff. also unix domain
7       sockets. and stuff.
8

SYNOPSIS

10          use AnyEvent::Socket;
11
12          tcp_connect "gameserver.deliantra.net", 13327, sub {
13             my ($fh) = @_
14                or die "gameserver.deliantra.net connect failed: $!";
15
16             # enjoy your filehandle
17          };
18
19          # a simple tcp server
20          tcp_server undef, 8888, sub {
21             my ($fh, $host, $port) = @_;
22
23             syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
24          };
25

DESCRIPTION

27       This module implements various utility functions for handling internet
28       protocol addresses and sockets, in an as transparent and simple way as
29       possible.
30
31       All functions documented without "AnyEvent::Socket::" prefix are
32       exported by default.
33
34       $ipn = parse_ipv4 $dotted_quad
35           Tries to parse the given dotted quad IPv4 address and return it in
36           octet form (or undef when it isn't in a parsable format). Supports
37           all forms specified by POSIX (e.g. 10.0.0.1, 10.1, "10.0x020304",
38           0x12345678 or 0377.0377.0377.0377).
39
40       $ipn = parse_ipv6 $textual_ipv6_address
41           Tries to parse the given IPv6 address and return it in octet form
42           (or undef when it isn't in a parsable format).
43
44           Should support all forms specified by RFC 2373 (and additionally
45           all IPv4 forms supported by parse_ipv4). Note that scope-id's are
46           not supported (and will not parse).
47
48           This function works similarly to "inet_pton AF_INET6, ...".
49
50           Example:
51
52              print unpack "H*", parse_ipv6 "2002:5345::10.0.0.1";
53              # => 2002534500000000000000000a000001
54
55       $token = parse_unix $hostname
56           This function exists mainly for symmetry to the other
57           "parse_protocol" functions - it takes a hostname and, if it is
58           "unix/", it returns a special address token, otherwise "undef".
59
60           The only use for this function is probably to detect whether a
61           hostname matches whatever AnyEvent uses for unix domain sockets.
62
63       $ipn = parse_address $ip
64           Combines "parse_ipv4" and "parse_ipv6" in one function. The address
65           here refers to the host address (not socket address) in network
66           form (binary).
67
68           If the $text is "unix/", then this function returns a special token
69           recognised by the other functions in this module to mean "UNIX
70           domain socket".
71
72           If the $text to parse is a mapped IPv4 in IPv6 address
73           (:ffff::<ipv4>), then it will be treated as an IPv4 address. If you
74           don't want that, you have to call "parse_ipv4" and/or "parse_ipv6"
75           manually.
76
77           Example:
78
79              print unpack "H*", parse_address "10.1.2.3";
80              # => 0a010203
81
82       $ipn = AnyEvent::Socket::aton $ip
83           Same as "parse_address", but not exported (think
84           "Socket::inet_aton" but without name resolution).
85
86       ($name, $aliases, $proto) = getprotobyname $name
87           Works like the builtin function of the same name, except it tries
88           hard to work even on broken platforms (well, that's windows), where
89           getprotobyname is traditionally very unreliable.
90
91           Example: get the protocol number for TCP (usually 6)
92
93              my $proto = getprotobyname "tcp";
94
95       ($host, $service) = parse_hostport $string[, $default_service]
96           Splitting a string of the form "hostname:port" is a common problem.
97           Unfortunately, just splitting on the colon makes it hard to specify
98           IPv6 addresses and doesn't support the less common but well
99           standardised "[ip literal]" syntax.
100
101           This function tries to do this job in a better way, it supports (at
102           least) the following formats, where "port" can be a numerical port
103           number of a service name, or a "name=port" string, and the " port"
104           and ":port" parts are optional. Also, everywhere where an IP
105           address is supported a hostname or unix domain socket address is
106           also supported (see "parse_unix"), and strings starting with "/"
107           will also be interpreted as unix domain sockets.
108
109              hostname:port    e.g. "www.linux.org", "www.x.de:443", "www.x.de:https=443",
110              ipv4:port        e.g. "198.182.196.56", "127.1:22"
111              ipv6             e.g. "::1", "affe::1"
112              [ipv4or6]:port   e.g. "[::1]", "[10.0.1]:80"
113              [ipv4or6] port   e.g. "[127.0.0.1]", "[www.x.org] 17"
114              ipv4or6 port     e.g. "::1 443", "10.0.0.1 smtp"
115              unix/:path       e.g. "unix/:/path/to/socket"
116              /path            e.g. "/path/to/socket"
117
118           It also supports defaulting the service name in a simple way by
119           using $default_service if no service was detected. If neither a
120           service was detected nor a default was specified, then this
121           function returns the empty list. The same happens when a parse
122           error was detected, such as a hostname with a colon in it (the
123           function is rather conservative, though).
124
125           Example:
126
127             print join ",", parse_hostport "localhost:443";
128             # => "localhost,443"
129
130             print join ",", parse_hostport "localhost", "https";
131             # => "localhost,https"
132
133             print join ",", parse_hostport "[::1]";
134             # => "," (empty list)
135
136             print join ",", parse_hostport "/tmp/debug.sock";
137             # => "unix/", "/tmp/debug.sock"
138
139       $string = format_hostport $host, $port
140           Takes a host (in textual form) and a port and formats in
141           unambigiously in a way that "parse_hostport" can parse it again.
142           $port can be "undef".
143
144       $sa_family = address_family $ipn
145           Returns the address family/protocol-family (AF_xxx/PF_xxx, in one
146           value :) of the given host address in network format.
147
148       $text = format_ipv4 $ipn
149           Expects a four octet string representing a binary IPv4 address and
150           returns its textual format. Rarely used, see "format_address" for a
151           nicer interface.
152
153       $text = format_ipv6 $ipn
154           Expects a sixteen octet string representing a binary IPv6 address
155           and returns its textual format. Rarely used, see "format_address"
156           for a nicer interface.
157
158       $text = format_address $ipn
159           Covnvert a host address in network format (e.g. 4 octets for IPv4
160           or 16 octets for IPv6) and convert it into textual form.
161
162           Returns "unix/" for UNIX domain sockets.
163
164           This function works similarly to "inet_ntop AF_INET || AF_INET6,
165           ...", except it automatically detects the address type.
166
167           Returns "undef" if it cannot detect the type.
168
169           If the $ipn is a mapped IPv4 in IPv6 address (:ffff::<ipv4>), then
170           just the contained IPv4 address will be returned. If you do not
171           want that, you have to call "format_ipv6" manually.
172
173           Example:
174
175              print format_address "\x01\x02\x03\x05";
176              => 1.2.3.5
177
178       $text = AnyEvent::Socket::ntoa $ipn
179           Same as format_address, but not exported (think "inet_ntoa").
180
181       inet_aton $name_or_address, $cb->(@addresses)
182           Works similarly to its Socket counterpart, except that it uses a
183           callback. Use the length to distinguish between ipv4 and ipv6 (4
184           octets for IPv4, 16 for IPv6), or use "format_address" to convert
185           it to a more readable format.
186
187           Note that "resolve_sockaddr", while initially a more complex
188           interface, resolves host addresses, IDNs, service names and SRV
189           records and gives you an ordered list of socket addresses to try
190           and should be preferred over "inet_aton".
191
192           Example.
193
194              inet_aton "www.google.com", my $cv = AE::cv;
195              say unpack "H*", $_
196                 for $cv->recv;
197              # => d155e363
198              # => d155e367 etc.
199
200              inet_aton "ipv6.google.com", my $cv = AE::cv;
201              say unpack "H*", $_
202                 for $cv->recv;
203              # => 20014860a00300000000000000000068
204
205       $sa = AnyEvent::Socket::pack_sockaddr $service, $host
206           Pack the given port/host combination into a binary sockaddr
207           structure. Handles both IPv4 and IPv6 host addresses, as well as
208           UNIX domain sockets ($host == "unix/" and $service == absolute
209           pathname).
210
211           Example:
212
213              my $bind = AnyEvent::Socket::pack_sockaddr 43, v195.234.53.120;
214              bind $socket, $bind
215                 or die "bind: $!";
216
217       ($service, $host) = AnyEvent::Socket::unpack_sockaddr $sa
218           Unpack the given binary sockaddr structure (as used by bind,
219           getpeername etc.) into a "$service, $host" combination.
220
221           For IPv4 and IPv6, $service is the port number and $host the host
222           address in network format (binary).
223
224           For UNIX domain sockets, $service is the absolute pathname and
225           $host is a special token that is understood by the other functions
226           in this module ("format_address" converts it to "unix/").
227
228       AnyEvent::Socket::resolve_sockaddr $node, $service, $proto, $family,
229       $type, $cb->([$family, $type, $proto, $sockaddr], ...)
230           Tries to resolve the given nodename and service name into protocol
231           families and sockaddr structures usable to connect to this node and
232           service in a protocol-independent way. It works remotely similar to
233           the getaddrinfo posix function.
234
235           For internet addresses, $node is either an IPv4 or IPv6 address, an
236           internet hostname (DNS domain name or IDN), and $service is either
237           a service name (port name from /etc/services) or a numerical port
238           number. If both $node and $service are names, then SRV records will
239           be consulted to find the real service, otherwise they will be used
240           as-is. If you know that the service name is not in your services
241           database, then you can specify the service in the format
242           "name=port" (e.g. "http=80").
243
244           If a host cannot be found via DNS, then it will be looked up in
245           /etc/hosts (or the file specified via $ENV{PERL_ANYEVENT_HOSTS}).
246           If they are found, the addresses there will be used. The effect is
247           as if entries from /etc/hosts would yield "A" and "AAAA" records
248           for the host name unless DNS already had records for them.
249
250           For UNIX domain sockets, $node must be the string "unix/" and
251           $service must be the absolute pathname of the socket. In this case,
252           $proto will be ignored.
253
254           $proto must be a protocol name, currently "tcp", "udp" or "sctp".
255           The default is currently "tcp", but in the future, this function
256           might try to use other protocols such as "sctp", depending on the
257           socket type and any SRV records it might find.
258
259           $family must be either 0 (meaning any protocol is OK), 4 (use only
260           IPv4) or 6 (use only IPv6). The default is influenced by
261           $ENV{PERL_ANYEVENT_PROTOCOLS}.
262
263           $type must be "SOCK_STREAM", "SOCK_DGRAM" or "SOCK_SEQPACKET" (or
264           "undef" in which case it gets automatically chosen to be
265           "SOCK_STREAM" unless $proto is "udp").
266
267           The callback will receive zero or more array references that
268           contain "$family, $type, $proto" for use in "socket" and a binary
269           $sockaddr for use in "connect" (or "bind").
270
271           The application should try these in the order given.
272
273           Example:
274
275              resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };
276
277       $guard = tcp_connect $host, $service, $connect_cb[, $prepare_cb]
278           This is a convenience function that creates a TCP socket and makes
279           a 100% non-blocking connect to the given $host (which can be a
280           DNS/IDN hostname or a textual IP address, or the string "unix/" for
281           UNIX domain sockets) and $service (which can be a numeric port
282           number or a service name, or a "servicename=portnumber" string, or
283           the pathname to a UNIX domain socket).
284
285           If both $host and $port are names, then this function will use SRV
286           records to locate the real target(s).
287
288           In either case, it will create a list of target hosts (e.g. for
289           multihomed hosts or hosts with both IPv4 and IPv6 addresses) and
290           try to connect to each in turn.
291
292           After the connection is established, then the $connect_cb will be
293           invoked with the socket file handle (in non-blocking mode) as
294           first, and the peer host (as a textual IP address) and peer port as
295           second and third arguments, respectively. The fourth argument is a
296           code reference that you can call if, for some reason, you don't
297           like this connection, which will cause "tcp_connect" to try the
298           next one (or call your callback without any arguments if there are
299           no more connections). In most cases, you can simply ignore this
300           argument.
301
302              $cb->($filehandle, $host, $port, $retry)
303
304           If the connect is unsuccessful, then the $connect_cb will be
305           invoked without any arguments and $! will be set appropriately
306           (with "ENXIO" indicating a DNS resolution failure).
307
308           The callback will never be invoked before "tcp_connect" returns,
309           even if "tcp_connect" was able to connect immediately (e.g. on unix
310           domain sockets).
311
312           The file handle is perfect for being plugged into AnyEvent::Handle,
313           but can be used as a normal perl file handle as well.
314
315           Unless called in void context, "tcp_connect" returns a guard object
316           that will automatically cancel the connection attempt when it gets
317           destroyed - in which case the callback will not be invoked.
318           Destroying it does not do anything to the socket after the connect
319           was successful - you cannot "uncall" a callback that has been
320           invoked already.
321
322           Sometimes you need to "prepare" the socket before connecting, for
323           example, to "bind" it to some port, or you want a specific connect
324           timeout that is lower than your kernel's default timeout. In this
325           case you can specify a second callback, $prepare_cb. It will be
326           called with the file handle in not-yet-connected state as only
327           argument and must return the connection timeout value (or 0,
328           "undef" or the empty list to indicate the default timeout is to be
329           used).
330
331           Note to the poor Microsoft Windows users: Windows (of course)
332           doesn't correctly signal connection errors, so unless your event
333           library works around this, failed connections will simply hang. The
334           only event libraries that handle this condition correctly are EV
335           and Glib. Additionally, AnyEvent works around this bug with Event
336           and in its pure-perl backend. All other libraries cannot correctly
337           handle this condition. To lessen the impact of this windows bug, a
338           default timeout of 30 seconds will be imposed on windows. Cygwin is
339           not affected.
340
341           Simple Example: connect to localhost on port 22.
342
343              tcp_connect localhost => 22, sub {
344                 my $fh = shift
345                    or die "unable to connect: $!";
346                 # do something
347              };
348
349           Complex Example: connect to www.google.com on port 80 and make a
350           simple GET request without much error handling. Also limit the
351           connection timeout to 15 seconds.
352
353              tcp_connect "www.google.com", "http",
354                 sub {
355                    my ($fh) = @_
356                       or die "unable to connect: $!";
357
358                    my $handle; # avoid direct assignment so on_eof has it in scope.
359                    $handle = new AnyEvent::Handle
360                       fh     => $fh,
361                       on_error => sub {
362                          AE::log error => $_[2];
363                          $_[0]->destroy;
364                       },
365                       on_eof => sub {
366                          $handle->destroy; # destroy handle
367                          AE::log info => "Done.";
368                       };
369
370                    $handle->push_write ("GET / HTTP/1.0\015\012\015\012");
371
372                    $handle->push_read (line => "\015\012\015\012", sub {
373                       my ($handle, $line) = @_;
374
375                       # print response header
376                       print "HEADER\n$line\n\nBODY\n";
377
378                       $handle->on_read (sub {
379                          # print response body
380                          print $_[0]->rbuf;
381                          $_[0]->rbuf = "";
382                       });
383                    });
384                 }, sub {
385                    my ($fh) = @_;
386                    # could call $fh->bind etc. here
387
388                    15
389                 };
390
391           Example: connect to a UNIX domain socket.
392
393              tcp_connect "unix/", "/tmp/.X11-unix/X0", sub {
394                 ...
395              }
396
397       $guard = tcp_server $host, $service, $accept_cb[, $prepare_cb]
398           Create and bind a stream socket to the given host address and port,
399           set the SO_REUSEADDR flag (if applicable) and call "listen". Unlike
400           the name implies, this function can also bind on UNIX domain
401           sockets.
402
403           For internet sockets, $host must be an IPv4 or IPv6 address (or
404           "undef", in which case it binds either to 0 or to "::", depending
405           on whether IPv4 or IPv6 is the preferred protocol, and maybe to
406           both in future versions, as applicable).
407
408           To bind to the IPv4 wildcard address, use 0, to bind to the IPv6
409           wildcard address, use "::".
410
411           The port is specified by $service, which must be either a service
412           name or a numeric port number (or 0 or "undef", in which case an
413           ephemeral port will be used).
414
415           For UNIX domain sockets, $host must be "unix/" and $service must be
416           the absolute pathname of the socket. This function will try to
417           "unlink" the socket before it tries to bind to it, and will try to
418           unlink it after it stops using it. See SECURITY CONSIDERATIONS,
419           below.
420
421           For each new connection that could be "accept"ed, call the
422           "$accept_cb->($fh, $host, $port)" with the file handle (in non-
423           blocking mode) as first, and the peer host and port as second and
424           third arguments (see "tcp_connect" for details).
425
426           Croaks on any errors it can detect before the listen.
427
428           In non-void context, this function returns a guard object whose
429           lifetime it tied to the TCP server: If the object gets destroyed,
430           the server will be stopped and the listening socket will be cleaned
431           up/unlinked (already accepted connections will not be affected).
432
433           When called in void-context, AnyEvent will keep the listening
434           socket alive internally. In this case, there is no guarantee that
435           the listening socket will be cleaned up or unlinked.
436
437           In all cases, when the function returns to the caller, the socket
438           is bound and in listening state.
439
440           If you need more control over the listening socket, you can provide
441           a "$prepare_cb->($fh, $host, $port)", which is called just before
442           the "listen ()" call, with the listen file handle as first
443           argument, and IP address and port number of the local socket
444           endpoint as second and third arguments.
445
446           It should return the length of the listen queue (or 0 for the
447           default).
448
449           Note to IPv6 users: RFC-compliant behaviour for IPv6 sockets
450           listening on "::" is to bind to both IPv6 and IPv4 addresses by
451           default on dual-stack hosts. Unfortunately, only GNU/Linux seems to
452           implement this properly, so if you want both IPv4 and IPv6
453           listening sockets you should create the IPv6 socket first and then
454           attempt to bind on the IPv4 socket, but ignore any "EADDRINUSE"
455           errors.
456
457           Example: bind on some TCP port on the local machine and tell each
458           client to go away.
459
460              tcp_server undef, undef, sub {
461                 my ($fh, $host, $port) = @_;
462
463                 syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
464              }, sub {
465                 my ($fh, $thishost, $thisport) = @_;
466                 AE::log info => "Bound to $thishost, port $thisport.";
467              };
468
469           Example: bind a server on a unix domain socket.
470
471              tcp_server "unix/", "/tmp/mydir/mysocket", sub {
472                 my ($fh) = @_;
473              };
474
475       $guard = AnyEvent::Socket::tcp_bind $host, $service, $done_cb[,
476       $prepare_cb]
477           Same as "tcp_server", except it doesn't call "accept" in a loop for
478           you but simply passes the listen socket to the $done_cb. This is
479           useful when you want to have a convenient set up for your listen
480           socket, but want to do the "accept"'ing yourself, for example, in
481           another process.
482
483           In case of an error, "tcp_bind" either croaks, or passes "undef" to
484           the $done_cb.
485
486           In non-void context, a guard will be returned. It will clean
487           up/unlink the listening socket when destroyed. In void context, no
488           automatic clean up might be performed.
489
490       tcp_nodelay $fh, $enable
491           Enables (or disables) the "TCP_NODELAY" socket option (also known
492           as Nagle's algorithm). Returns false on error, true otherwise.
493
494       tcp_congestion $fh, $algorithm
495           Sets the tcp congestion avoidance algorithm (via the
496           "TCP_CONGESTION" socket option). The default is OS-specific, but is
497           usually "reno". Typical other available choices include "cubic",
498           "lp", "bic", "highspeed", "htcp", "hybla", "illinois", "scalable",
499           "vegas", "veno", "westwood" and "yeah".
500

SECURITY CONSIDERATIONS

502       This module is quite powerful, with with power comes the ability to
503       abuse as well: If you accept "hostnames" and ports from untrusted
504       sources, then note that this can be abused to delete files
505       (host="unix/"). This is not really a problem with this module, however,
506       as blindly accepting any address and protocol and trying to bind a
507       server or connect to it is harmful in general.
508

AUTHOR

510        Marc Lehmann <schmorp@schmorp.de>
511        http://anyevent.schmorp.de
512
513
514
515perl v5.28.0                      2016-12-12               AnyEvent::Socket(3)
Impressum