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