The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

AnyEvent::Socket - useful IPv4 and IPv6 stuff.

SYNOPSIS

 use AnyEvent::Socket;

DESCRIPTION

This module implements various utility functions for handling internet protocol addresses and sockets, in an as transparent and simple way as possible.

All functions documented without AnyEvent::Socket:: prefix are exported by default.

$ipn = parse_ipv4 $dotted_quad

Tries to parse the given dotted quad IPv4 address and return it in octet form (or undef when it isn't in a parsable format). Supports all forms specified by POSIX (e.g. 10.0.0.1, 10.1, 10.0x020304, 0x12345678 or 0377.0377.0377.0377).

$ipn = parse_ipv6 $textual_ipv6_address

Tries to parse the given IPv6 address and return it in octet form (or undef when it isn't in a parsable format).

Should support all forms specified by RFC 2373 (and additionally all IPv4 forms supported by parse_ipv4).

This function works similarly to inet_pton AF_INET6, ....

$ipn = parse_ip $text

Combines parse_ipv4 and parse_ipv6 in one function.

$text = format_ip $ipn

Takes either an IPv4 address (4 octets) or and IPv6 address (16 octets) and converts it into textual form.

This function works similarly to inet_ntop AF_INET || AF_INET6, ..., except it automatically detects the address type.

inet_aton $name_or_address, $cb->(@addresses)

Works similarly to its Socket counterpart, except that it uses a callback. Also, if a host has only an IPv6 address, this might be passed to the callback instead (use the length to detect this - 4 for IPv4, 16 for IPv6).

Unlike the Socket function of the same name, you can get multiple IPv4 and IPv6 addresses as result.

$sa = AnyEvent::Socket::pack_sockaddr $port, $host

Pack the given port/host combination into a binary sockaddr structure. Handles both IPv4 and IPv6 host addresses.

($port, $host) = AnyEvent::Socket::unpack_sockaddr $sa

Unpack the given binary sockaddr structure (as used by bind, getpeername etc.) into a $port, $host combination.

Handles both IPv4 and IPv6 sockaddr structures.

$guard = tcp_connect $host, $service, $connect_cb[, $prepare_cb]

This is a convenience function that creates a TCP socket and makes a 100% non-blocking connect to the given $host (which can be a hostname or a textual IP address) and $service (which can be a numeric port number or a service name, or a servicename=portnumber string).

If both $host and $port are names, then this function will use SRV records to locate the real target(s).

In either case, it will create a list of target hosts (e.g. for multihomed hosts or hosts with both IPv4 and IPv6 addresses) and try to connect to each in turn.

If the connect is successful, then the $connect_cb will be invoked with the socket file handle (in non-blocking mode) as first and the peer host (as a textual IP address) and peer port as second and third arguments, respectively. The fourth argument is a code reference that you can call if, for some reason, you don't like this connection, which will cause tcp_connect to try the next one (or call your callback without any arguments if there are no more connections). In most cases, you can simply ignore this argument.

   $cb->($filehandle, $host, $port, $retry)

If the connect is unsuccessful, then the $connect_cb will be invoked without any arguments and $! will be set appropriately (with ENXIO indicating a DNS resolution failure).

The file handle is perfect for being plugged into AnyEvent::Handle, but can be used as a normal perl file handle as well.

Unless called in void context, tcp_connect returns a guard object that will automatically abort connecting when it gets destroyed (it does not do anything to the socket after the connect was successful).

Sometimes you need to "prepare" the socket before connecting, for example, to bind it to some port, or you want a specific connect timeout that is lower than your kernel's default timeout. In this case you can specify a second callback, $prepare_cb. It will be called with the file handle in not-yet-connected state as only argument and must return the connection timeout value (or 0, undef or the empty list to indicate the default timeout is to be used).

Note that the socket could be either a IPv4 TCP socket or an IPv6 TCP socket (although only IPv4 is currently supported by this module).

Simple Example: connect to localhost on port 22.

  tcp_connect localhost => 22, sub {
     my $fh = shift
        or die "unable to connect: $!";
     # do something
  };

Complex Example: connect to www.google.com on port 80 and make a simple GET request without much error handling. Also limit the connection timeout to 15 seconds.

   tcp_connect "www.google.com", "http",
      sub {
         my ($fh) = @_
            or die "unable to connect: $!";

         my $handle; # avoid direct assignment so on_eof has it in scope.
         $handle = new AnyEvent::Handle
            fh     => $fh,
            on_eof => sub {
               undef $handle; # keep it alive till eof
               warn "done.\n";
            };

         $handle->push_write ("GET / HTTP/1.0\015\012\015\012");

         $handle->push_read_line ("\015\012\015\012", sub {
            my ($handle, $line) = @_;

            # print response header
            print "HEADER\n$line\n\nBODY\n";

            $handle->on_read (sub {
               # print response body
               print $_[0]->rbuf;
               $_[0]->rbuf = "";
            });
         });
      }, sub {
         my ($fh) = @_;
         # could call $fh->bind etc. here

         15
      };
$guard = tcp_server $host, $port, $accept_cb[, $prepare_cb]

Create and bind a TCP socket to the given host (any IPv4 host if undef, otherwise it must be an IPv4 or IPv6 address) and port (service name or numeric port number, or an ephemeral port if given as zero or undef), set the SO_REUSEADDR flag and call listen.

For each new connection that could be accepted, call the $accept_cb with the file handle (in non-blocking mode) as first and the peer host and port as second and third arguments (see tcp_connect for details).

Croaks on any errors.

If called in non-void context, then this function returns a guard object whose lifetime it tied to the TCP server: If the object gets destroyed, the server will be stopped (but existing accepted connections will continue).

If you need more control over the listening socket, you can provide a $prepare_cb, which is called just before the listen () call, with the listen file handle as first argument.

It should return the length of the listen queue (or 0 for the default).

Example: bind on TCP port 8888 on the local machine and tell each client to go away.

   tcp_server undef, 8888, sub {
      my ($fh, $host, $port) = @_;

      syswrite $fh, "The internet is full, $host:$port. Go away!\015\012";
   };

AUTHOR

 Marc Lehmann <schmorp@schmorp.de>
 http://home.schmorp.de/