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