IO-Socket-IP-0.25000755001750001750 012264276575 12244 5ustar00leoleo000000000000IO-Socket-IP-0.25/Changes000444001750001750 1471612264276575 13725 0ustar00leoleo000000000000Revision history for IO-Socket-IP 0.25 2014/01/11 17:19:29 [BUGFIXES] * Allow both *Host with port and *Port arguments, letting port from Host argument take precedence (INET compat) * Ensure that a Host/Family-less constructor still constructs a socket, by using gai()s AI_ADDRCONFIG hint 0.24 2013/09/19 14:17:22 [BUGFIXES] * Defend against INADDR_LOOPBACK not being 127.0.0.1 on machines with odd networking (e.g. FreeBSD jails) during unit testing 0.23 2013/09/11 17:53:19 [BUGFIXES] * Check that kernel actually supports SO_REUSEPORT before unit-testing it (RT86177) 0.22 BUGFIXES: * Always pass 'socktype' hint to getaddrinfo() in unit tests because some OSes get upset without it * Don't unit-test that sockaddr is updated with a local bind() on SOCK_DGRAM sockets because some OSes don't 0.21 CHANGES: * Provide a downgrade method to turn an AF_INET-domain socket into a real IO::Socket::INET instance * Ensure that IO::Socket->new( Domain => ... ) definitely returns a socket in the right family 0.20 CHANGES: * Skip the IPV6_V6ONLY tests on machines lacking that constant * Avoid Socket::inet_pton() in unit tests as Strawberry lacks it * Added ->join_addr * Respect subclassing argument to ->accept 0.19 CHANGES: * More IO::Socket::INET compatibility fixes: + Ensure ->connected is false after ->close + Ensure that IO::Socket::IP->new(Family => $family) still creates an unbound, unconnected socket filehandle 0.18 CHANGES: * Work around ->socktype being undef on IO::Socket versions before 1.35 by fetching ->sockopt( SO_TYPE ) (RT81549) BUGFIXES: * Fix test skip counts in t/21nonblocking-connect-internet.t (RT79393) 0.17 CHANGES: * Only pass AI_ADDRCONFIG as getaddrinfo() flag if no other flags specified, so the caller can disable it if required. BUGFIXES: * Don't count select() invocations during nonblocking unit test because this is too unreliable and races with the kernel/TCP stack 0.16 BUGFIXES: * Don't ->close after all connect attempts fail, because IO::Socket::INET doesn't do that 0.15 BUGFIXES: * (Hopefully) improved ->connect logic for better MSWin32 support * Skip testing AI_NUMERICSERV on OSes that don't support it 0.14 BUGFIXES: * Second attempt at fixing test skip counts 0.13 BUGFIXES: * Updated test skip counts in unit tests so they match the number of tests actually skipped 0.12 CHANGES: * Ensure that all instances have a defined fileno after construction, even in non-blocking mode (RT77726) 0.11 CHANGES: * Ignore unrecognised constructor arguments rather than complaining about their presence (RT77536) * Call $self->connect during constructor because IO::Socket::SSL relies on this to happen (RT77536) 0.10 CHANGES: * Allow specifying other getaddrinfo flags using GetAddrInfoFlags constructor argument (RT75783) * Provide a convenient hostname+port string splitting utility method 0.09 CHANGES: * Attempt to implement IPV6_V6ONLY sockopt wrapper - not all OSes can disable it, so detect and skip those * Provide ->sockaddr and ->peeraddr convenience accessors, same as IO::Socket::INET (RT75071) * Use new NIx_NOHOST and NIx_NOSERV flags to avoid redundant getnameinfo() lookups when only one of host or service name is required * Ensure that errno gets set to EINVAL on getaddrinfo() failures BUGFIXES: * Ignore existing-but-undefined constructor arguments * Avoid locale-specific error message testing of $! * Updates to unit tests for cygwin 0.08 CHANGES: * Depend on Socket 1.95 now a full dual-life release has been made * Set the AI_ADDRCONFIG getaddrinfo hint * Fix some spelling mistakes/typoes * MSWin32 fixes: + MSWin32 uses select() exceptfds rather than writefds to report on nonblocking connect() failure + MSWin32 uses EWOULDBLOCK rather than EINPROGRESS to indicate nonblocking connect() BUGFIXES: * Ensure ->socket protocol argument is always defined * Bugfix for (e.g.) NetBSD, which gets upset at protocol hint without socktype hint to getaddrinfo() * Pass 'type' rather than 'proto' to constructor in t/11sockopts.t to avoid MSWin32 test failures * Localise $1/$2 to placate [perl #67962] 0.07 CHANGES: * Prepare for Socket::getaddrinfo() in core; prefer it to Socket::GetAddrInfo::getaddrinfo() * Implement Family constructor arg * Optional registration with IO::Socket * Documentation rewordings * Bugfix to local socket connect tests - test using blocking rather than nonblocking sockets to guarantee synchronous packet delivery * Bugfix to t/04, t/05 - skip if unable to bind ::1 0.06 CHANGES: * Implement nonblocking connect * Implement LocalAddrInfo and PeerAddrInfo args * Example of nonblocking usage, using Net::LibAsyncNS 0.05 CHANGES: * Implement combined ->bind and ->connect operations * Accept "host:service" as *Addr args, and PeerAddr as sole constructor argument * Accept "name(port)" as service arguments 0.04 CHANGES: * Try to yield the most appropriate connect/bind/socket error * Implement sockhost/peerhost methods to match ::INET, moved hostname methods to sockhostname/peerhostname BUGFIXES: * Work around IO::Socket bug where ->accept'ed sockets do not get ->sockdomain or ->socktype 0.03 CHANGES: * Set $@ to raise error messages from constructor BUGFIXES: * Correctly implement 'Type' constructor argument * Test SO_BROADCAST on udp instead of tcp as some OSes forbid it 0.02 BUGFIXES: * Not all OSes return true sockopts as 1; test simply for non-zero * Gracefully skip IPv6 tests if Socket6 unavailable 0.01 First version, released on an unsuspecting world. IO-Socket-IP-0.25/META.json000444001750001750 162712264276575 14030 0ustar00leoleo000000000000{ "abstract" : "Family-neutral IP socket supporting both IPv4 and IPv6", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4202", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "IO-Socket-IP", "prereqs" : { "build" : { "requires" : { "Test::More" : "0.88" } }, "runtime" : { "requires" : { "IO::Socket" : "0", "Socket" : "1.97" } } }, "provides" : { "IO::Socket::IP" : { "file" : "lib/IO/Socket/IP.pm", "version" : "0.25" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.25" } IO-Socket-IP-0.25/README000444001750001750 4175312264276575 13313 0ustar00leoleo000000000000NAME `IO::Socket::IP' - Family-neutral IP socket supporting both IPv4 and IPv6 SYNOPSIS use IO::Socket::IP; my $sock = IO::Socket::IP->new( PeerHost => "www.google.com", PeerPort => "http", Type => SOCK_STREAM, ) or die "Cannot construct socket - $@"; my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" : ( $sock->sockdomain == PF_INET ) ? "IPv4" : "unknown"; printf "Connected to google via %s\n", $familyname; DESCRIPTION This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a replacement for IO::Socket::INET. Most constructor arguments and methods are provided in a backward-compatible way. For a list of known differences, see the `IO::Socket::INET' INCOMPATIBILITES section below. It uses the `getaddrinfo(3)' function to convert hostnames and service names or port numbers into sets of possible addresses to connect to or listen on. This allows it to work for IPv6 where the system supports it, while still falling back to IPv4-only on systems which don't. REPLACING `IO::Socket' DEFAULT BEHAVIOUR By placing `-register' in the import list, `IO::Socket' uses `IO::Socket::IP' rather than `IO::Socket::INET' as the class that handles `PF_INET'. `IO::Socket' will also use `IO::Socket::IP' rather than `IO::Socket::INET6' to handle `PF_INET6', provided that the `AF_INET6' constant is available. Changing `IO::Socket''s default behaviour means that calling the `IO::Socket' constructor with either `PF_INET' or `PF_INET6' as the `Domain' parameter will yield an `IO::Socket::IP' object. use IO::Socket::IP -register; my $sock = IO::Socket->new( Domain => PF_INET6, LocalHost => "::1", Listen => 1, ) or die "Cannot create socket - $@\n"; print "Created a socket of type " . ref($sock) . "\n"; Note that `-register' is a global setting that applies to the entire program; it cannot be applied only for certain callers, removed, or limited by lexical scope. CONSTRUCTORS $sock = IO::Socket::IP->new( %args ) Creates a new `IO::Socket::IP' object, containing a newly created socket handle according to the named arguments passed. The recognised arguments are: PeerHost => STRING PeerService => STRING Hostname and service name for the peer to `connect()' to. The service name may be given as a port number, as a decimal string. PeerAddr => STRING PeerPort => STRING For symmetry with the accessor methods and compatibility with `IO::Socket::INET', these are accepted as synonyms for `PeerHost' and `PeerService' respectively. PeerAddrInfo => ARRAY Alternate form of specifying the peer to `connect()' to. This should be an array of the form returned by `Socket::getaddrinfo'. This parameter takes precedence over the `Peer*', `Family', `Type' and `Proto' arguments. LocalHost => STRING LocalService => STRING Hostname and service name for the local address to `bind()' to. LocalAddr => STRING LocalPort => STRING For symmetry with the accessor methods and compatibility with `IO::Socket::INET', these are accepted as synonyms for `LocalHost' and `LocalService' respectively. LocalAddrInfo => ARRAY Alternate form of specifying the local address to `bind()' to. This should be an array of the form returned by `Socket::getaddrinfo'. This parameter takes precedence over the `Local*', `Family', `Type' and `Proto' arguments. Family => INT The address family to pass to `getaddrinfo' (e.g. `AF_INET', `AF_INET6'). Normally this will be left undefined, and `getaddrinfo' will search using any address family supported by the system. Type => INT The socket type to pass to `getaddrinfo' (e.g. `SOCK_STREAM', `SOCK_DGRAM'). Normally defined by the caller; if left undefined `getaddrinfo' may attempt to infer the type from the service name. Proto => STRING or INT The IP protocol to use for the socket (e.g. `'tcp'', `IPPROTO_TCP', `'udp'',`IPPROTO_UDP'). Normally this will be left undefined, and either `getaddrinfo' or the kernel will choose an appropriate value. May be given either in string name or numeric form. GetAddrInfoFlags => INT More flags to pass to the `getaddrinfo()' function. If not supplied, a default of `AI_ADDRCONFIG' will be used. These flags will be combined with `AI_PASSIVE' if the `Listen' argument is given. For more information see the documentation about `getaddrinfo()' in the Socket module. Listen => INT If defined, puts the socket into listening mode where new connections can be accepted using the `accept' method. The value given is used as the `listen(2)' queue size. ReuseAddr => BOOL If true, set the `SO_REUSEADDR' sockopt ReusePort => BOOL If true, set the `SO_REUSEPORT' sockopt (not all OSes implement this sockopt) Broadcast => BOOL If true, set the `SO_BROADCAST' sockopt V6Only => BOOL If defined, set the `IPV6_V6ONLY' sockopt when creating `PF_INET6' sockets to the given value. If true, a listening-mode socket will only listen on the `AF_INET6' addresses; if false it will also accept connections from `AF_INET' addresses. If not defined, the socket option will not be changed, and default value set by the operating system will apply. For repeatable behaviour across platforms it is recommended this value always be defined for listening-mode sockets. Note that not all platforms support disabling this option. Some, at least OpenBSD and MirBSD, will fail with `EINVAL' if you attempt to disable it. To determine whether it is possible to disable, you may use the class method if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) { ... } else { ... } If your platform does not support disabling this option but you still want to listen for both `AF_INET' and `AF_INET6' connections you will have to create two listening sockets, one bound to each protocol. Timeout This `IO::Socket::INET'-style argument is not currently supported. See the `IO::Socket::INET' INCOMPATIBILITES section below. MultiHomed This `IO::Socket::INET'-style argument is ignored, except if it is defined but false. See the `IO::Socket::INET' INCOMPATIBILITES section below. However, the behaviour it enables is always performed by `IO::Socket::IP'. Blocking => BOOL If defined but false, the socket will be set to non-blocking mode. Otherwise it will default to blocking mode. See the NON-BLOCKING section below for more detail. If neither `Type' nor `Proto' hints are provided, a default of `SOCK_STREAM' and `IPPROTO_TCP' respectively will be set, to maintain compatibility with `IO::Socket::INET'. Other named arguments that are not recognised are ignored. If the constructor fails, it will set `$@' to an appropriate error message; this may be from `$!' or it may be some other string; not every failure necessarily has an associated `errno' value. $sock = IO::Socket::IP->new( $peeraddr ) As a special case, if the constructor is passed a single argument (as opposed to an even-sized list of key/value pairs), it is taken to be the value of the `PeerAddr' parameter. This is parsed in the same way, according to the behaviour given in the `PeerHost' AND `LocalHost' PARSING section below. METHODS As well as the following methods, this class inherits all the methods in IO::Socket and IO::Handle. ( $host, $service ) = $sock->sockhost_service( $numeric ) Returns the hostname and service name of the local address (that is, the socket address given by the `sockname' method). If `$numeric' is true, these will be given in numeric form rather than being resolved into names. The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call `getnameinfo(3)' only once. $addr = $sock->sockhost Return the numeric form of the local address as a textual representation $port = $sock->sockport Return the numeric form of the local port number $host = $sock->sockhostname Return the resolved name of the local address $service = $sock->sockservice Return the resolved name of the local port number $addr = $sock->sockaddr Return the local address as a binary octet string ( $host, $service ) = $sock->peerhost_service( $numeric ) Returns the hostname and service name of the peer address (that is, the socket address given by the `peername' method), similar to the `sockhost_service' method. The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call `getnameinfo(3)' only once. $addr = $sock->peerhost Return the numeric form of the peer address as a textual representation $port = $sock->peerport Return the numeric form of the peer port number $host = $sock->peerhostname Return the resolved name of the peer address $service = $sock->peerservice Return the resolved name of the peer port number $addr = $peer->peeraddr Return the peer address as a binary octet string $inet = $sock->as_inet Returns a new IO::Socket::INET instance wrapping the same filehandle. This may be useful in cases where it is required, for backward-compatibility, to have a real object of `IO::Socket::INET' type instead of `IO::Socket::IP'. The new object will wrap the same underlying socket filehandle as the original, so care should be taken not to continue to use both objects concurrently. Ideally the original `$sock' should be discarded after this method is called. This method checks that the socket domain is `PF_INET' and will throw an exception if it isn't. NON-BLOCKING If the constructor is passed a defined but false value for the `Blocking' argument then the socket is put into non-blocking mode. When in non-blocking mode, the socket will not be set up by the time the constructor returns, because the underlying `connect(2)' syscall would otherwise have to block. The non-blocking behaviour is an extension of the `IO::Socket::INET' API, unique to `IO::Socket::IP', because the former does not support multi-homed non-blocking connect. When using non-blocking mode, the caller must repeatedly check for writeability on the filehandle (for instance using `select' or `IO::Poll'). Each time the filehandle is ready to write, the `connect' method must be called, with no arguments. Note that some operating systems, most notably `MSWin32' do not report a `connect()' failure using write-ready; so you must also `select()' for exceptional status. While `connect' returns false, the value of `$!' indicates whether it should be tried again (by being set to the value `EINPROGRESS', or `EWOULDBLOCK' on MSWin32), or whether a permanent error has occurred (e.g. `ECONNREFUSED'). Once the socket has been connected to the peer, `connect' will return true and the socket will now be ready to use. Note that calls to the platform's underlying `getaddrinfo(3)' function may block. If `IO::Socket::IP' has to perform this lookup, the constructor will block even when in non-blocking mode. To avoid this blocking behaviour, the caller should pass in the result of such a lookup using the `PeerAddrInfo' or `LocalAddrInfo' arguments. This can be achieved by using Net::LibAsyncNS, or the `getaddrinfo(3)' function can be called in a child process. use IO::Socket::IP; use Errno qw( EINPROGRESS EWOULDBLOCK ); my @peeraddrinfo = ... # Caller must obtain the getaddinfo result here my $socket = IO::Socket::IP->new( PeerAddrInfo => \@peeraddrinfo, Blocking => 0, ) or die "Cannot construct socket - $@"; while( !$socket->connect and ( $! == EINPROGRESS || $! == EWOULDBLOCK ) ) { my $wvec = ''; vec( $wvec, fileno $socket, 1 ) = 1; my $evec = ''; vec( $evec, fileno $socket, 1 ) = 1; select( undef, $wvec, $evec, undef ) or die "Cannot select - $!"; } die "Cannot connect - $!" if $!; ... The example above uses `select()', but any similar mechanism should work analogously. `IO::Socket::IP' takes care when creating new socket filehandles to preserve the actual file descriptor number, so such techniques as `poll' or `epoll' should be transparent to its reallocation of a different socket underneath, perhaps in order to switch protocol family between `PF_INET' and `PF_INET6'. For another example using `IO::Poll' and `Net::LibAsyncNS', see the examples/nonblocking_libasyncns.pl file in the module distribution. `PeerHost' AND `LocalHost' PARSING To support the `IO::Socket::INET' API, the host and port information may be passed in a single string rather than as two separate arguments. If either `LocalHost' or `PeerHost' (or their `...Addr' synonyms) have any of the following special forms then special parsing is applied. The value of the `...Host' argument will be split to give both the hostname and port (or service name): hostname.example.org:http # Host name 192.0.2.1:80 # IPv4 address [2001:db8::1]:80 # IPv6 address In each case, the port or service name (e.g. `80') is passed as the `LocalService' or `PeerService' argument. Either of `LocalService' or `PeerService' (or their `...Port' synonyms) can be either a service name, a decimal number, or a string containing both a service name and number, in a form such as http(80) In this case, the name (`http') will be tried first, but if the resolver does not understand it then the port number (`80') will be used instead. If the `...Host' argument is in this special form and the corresponding `...Service' or `...Port' argument is also defined, the one parsed from the `...Host' argument will take precedence and the other will be ignored. ( $host, $port ) = IO::Socket::IP->split_addr( $addr ) Utility method that provides the parsing functionality described above. Returns a 2-element list, containing either the split hostname and port description if it could be parsed, or the given address and `undef' if it was not recognised. IO::Socket::IP->split_addr( "hostname:http" ) # ( "hostname", "http" ) IO::Socket::IP->split_addr( "192.0.2.1:80" ) # ( "192.0.2.1", "80" ) IO::Socket::IP->split_addr( "[2001:db8::1]:80" ) # ( "2001:db8::1", "80" ) IO::Socket::IP->split_addr( "something.else" ) # ( "something.else", undef ) $addr = IO::Socket::IP->join_addr( $host, $port ) Utility method that performs the reverse of `split_addr', returning a string formed by joining the specified host address and port number. The host address will be wrapped in `[]' brackets if required (because it is a raw IPv6 numeric address). This can be especially useful when combined with the `sockhost_service' or `peerhost_service' methods. say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service ); `IO::Socket::INET' INCOMPATIBILITES * The `Timeout' constructor argument is currently not recognised. The behaviour enabled by `MultiHomed' is in fact implemented by `IO::Socket::IP' as it is required to correctly support searching for a useable address from the results of the `getaddrinfo(3)' call. The constructor will ignore the value of this argument, except if it is defined but false. An exception is thrown in this case, because that would request it disable the `getaddrinfo(3)' search behaviour in the first place. TODO * Investigate whether `POSIX::dup2' upsets BSD's `kqueue' watchers, and if so, consider what possible workarounds might be applied. AUTHOR Paul Evans IO-Socket-IP-0.25/Build.PL000444001750001750 73612264276575 13663 0ustar00leoleo000000000000use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => 'IO::Socket::IP', requires => { 'IO::Socket' => 0, 'Socket' => '1.97', }, build_requires => { 'Test::More' => '0.88', # done_testing }, auto_configure_requires => 0, # Don't add M::B to configure_requires license => 'perl', create_makefile_pl => 'traditional', create_license => 1, create_readme => 1, ); $build->create_build_script; IO-Socket-IP-0.25/LICENSE000444001750001750 4376012264276575 13440 0ustar00leoleo000000000000This software is copyright (c) 2014 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2014 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Suite 500, Boston, MA 02110-1335 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2014 by Paul Evans . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End IO-Socket-IP-0.25/META.yml000444001750001750 106412264276575 13653 0ustar00leoleo000000000000--- abstract: 'Family-neutral IP socket supporting both IPv4 and IPv6' author: - 'Paul Evans ' build_requires: Test::More: 0.88 dynamic_config: 1 generated_by: 'Module::Build version 0.4202, CPAN::Meta::Converter version 2.133380' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: IO-Socket-IP provides: IO::Socket::IP: file: lib/IO/Socket/IP.pm version: 0.25 requires: IO::Socket: 0 Socket: 1.97 resources: license: http://dev.perl.org/licenses/ version: 0.25 IO-Socket-IP-0.25/MANIFEST000444001750001750 105312264276575 13531 0ustar00leoleo000000000000Build.PL Changes examples/connect.pl examples/nonblocking_libasyncns.pl lib/IO/Socket/IP.pm LICENSE Makefile.PL MANIFEST This list of files META.json META.yml README t/00use.t t/01local-client-v4.t t/02local-server-v4.t t/03local-cross-v4.t t/04local-client-v6.t t/05local-server-v6.t t/06local-cross-v6.t t/10args.t t/11sockopts.t t/12port-fallback.t t/13addrinfo.t t/14fileno.t t/15io-socket.t t/16v6only.t t/17gai-flags.t t/18fdopen.t t/19no-addrs.t t/20subclass.t t/21as-inet.t t/30nonblocking-connect.t t/31nonblocking-connect-internet.t t/99pod.t IO-Socket-IP-0.25/Makefile.PL000444001750001750 64412264276575 14337 0ustar00leoleo000000000000# Note: this file was auto-generated by Module::Build::Compat version 0.4202 use ExtUtils::MakeMaker; WriteMakefile ( 'NAME' => 'IO::Socket::IP', 'VERSION_FROM' => 'lib/IO/Socket/IP.pm', 'PREREQ_PM' => { 'IO::Socket' => 0, 'Socket' => '1.97', 'Test::More' => '0.88' }, 'INSTALLDIRS' => 'site', 'EXE_FILES' => [], 'PL_FILES' => {} ) ; IO-Socket-IP-0.25/lib000755001750001750 012264276575 13012 5ustar00leoleo000000000000IO-Socket-IP-0.25/lib/IO000755001750001750 012264276575 13321 5ustar00leoleo000000000000IO-Socket-IP-0.25/lib/IO/Socket000755001750001750 012264276575 14551 5ustar00leoleo000000000000IO-Socket-IP-0.25/lib/IO/Socket/IP.pm000444001750001750 10262512264276575 15622 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2010-2014 -- leonerd@leonerd.org.uk package IO::Socket::IP; use strict; use warnings; use base qw( IO::Socket ); our $VERSION = '0.25'; use Carp; use Socket 1.97 qw( getaddrinfo getnameinfo sockaddr_family AF_INET AI_PASSIVE IPPROTO_TCP IPPROTO_UDP IPPROTO_IPV6 IPV6_V6ONLY NI_DGRAM NI_NUMERICHOST NI_NUMERICSERV NIx_NOHOST NIx_NOSERV SO_REUSEADDR SO_REUSEPORT SO_BROADCAST SO_ERROR SOCK_DGRAM SOCK_STREAM SOL_SOCKET ); my $AF_INET6 = eval { Socket::AF_INET6() }; # may not be defined my $AI_ADDRCONFIG = eval { Socket::AI_ADDRCONFIG() } || 0; use POSIX qw( dup2 ); use Errno qw( EINVAL EINPROGRESS EISCONN ); use constant HAVE_MSWIN32 => ( $^O eq "MSWin32" ); my $IPv6_re = do { # translation of RFC 3986 3.2.2 ABNF to re my $IPv4address = do { my $dec_octet = q<(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])>; qq<$dec_octet(?: \\. $dec_octet){3}>; }; my $IPv6address = do { my $h16 = qq<[0-9A-Fa-f]{1,4}>; my $ls32 = qq<(?: $h16 : $h16 | $IPv4address)>; qq<(?: (?: $h16 : ){6} $ls32 | :: (?: $h16 : ){5} $ls32 | (?: $h16 )? :: (?: $h16 : ){4} $ls32 | (?: (?: $h16 : ){0,1} $h16 )? :: (?: $h16 : ){3} $ls32 | (?: (?: $h16 : ){0,2} $h16 )? :: (?: $h16 : ){2} $ls32 | (?: (?: $h16 : ){0,3} $h16 )? :: $h16 : $ls32 | (?: (?: $h16 : ){0,4} $h16 )? :: $ls32 | (?: (?: $h16 : ){0,5} $h16 )? :: $h16 | (?: (?: $h16 : ){0,6} $h16 )? :: )> }; qr<$IPv6address>xo; }; =head1 NAME C - Family-neutral IP socket supporting both IPv4 and IPv6 =head1 SYNOPSIS use IO::Socket::IP; my $sock = IO::Socket::IP->new( PeerHost => "www.google.com", PeerPort => "http", Type => SOCK_STREAM, ) or die "Cannot construct socket - $@"; my $familyname = ( $sock->sockdomain == PF_INET6 ) ? "IPv6" : ( $sock->sockdomain == PF_INET ) ? "IPv4" : "unknown"; printf "Connected to google via %s\n", $familyname; =head1 DESCRIPTION This module provides a protocol-independent way to use IPv4 and IPv6 sockets, intended as a replacement for L. Most constructor arguments and methods are provided in a backward-compatible way. For a list of known differences, see the C INCOMPATIBILITES section below. It uses the C function to convert hostnames and service names or port numbers into sets of possible addresses to connect to or listen on. This allows it to work for IPv6 where the system supports it, while still falling back to IPv4-only on systems which don't. =head1 REPLACING C DEFAULT BEHAVIOUR By placing C<-register> in the import list, C uses C rather than C as the class that handles C. C will also use C rather than C to handle C, provided that the C constant is available. Changing C's default behaviour means that calling the C constructor with either C or C as the C parameter will yield an C object. use IO::Socket::IP -register; my $sock = IO::Socket->new( Domain => PF_INET6, LocalHost => "::1", Listen => 1, ) or die "Cannot create socket - $@\n"; print "Created a socket of type " . ref($sock) . "\n"; Note that C<-register> is a global setting that applies to the entire program; it cannot be applied only for certain callers, removed, or limited by lexical scope. =cut sub import { my $pkg = shift; my @symbols; foreach ( @_ ) { if( $_ eq "-register" ) { IO::Socket::IP::_ForINET->register_domain( AF_INET ); IO::Socket::IP::_ForINET6->register_domain( $AF_INET6 ) if defined $AF_INET6; } else { push @symbols, $_; } } @_ = ( $pkg, @symbols ); goto &IO::Socket::import; } # Convenient capability test function { my $can_disable_v6only; sub CAN_DISABLE_V6ONLY { return $can_disable_v6only if defined $can_disable_v6only; socket my $testsock, Socket::PF_INET6(), SOCK_STREAM, 0 or die "Cannot socket(PF_INET6) - $!"; if( setsockopt $testsock, IPPROTO_IPV6, IPV6_V6ONLY, 0 ) { return $can_disable_v6only = 1; } elsif( $! == EINVAL ) { return $can_disable_v6only = 0; } else { die "Cannot setsockopt() - $!"; } } } =head1 CONSTRUCTORS =cut =head2 $sock = IO::Socket::IP->new( %args ) Creates a new C object, containing a newly created socket handle according to the named arguments passed. The recognised arguments are: =over 8 =item PeerHost => STRING =item PeerService => STRING Hostname and service name for the peer to C to. The service name may be given as a port number, as a decimal string. =item PeerAddr => STRING =item PeerPort => STRING For symmetry with the accessor methods and compatibility with C, these are accepted as synonyms for C and C respectively. =item PeerAddrInfo => ARRAY Alternate form of specifying the peer to C to. This should be an array of the form returned by C. This parameter takes precedence over the C, C, C and C arguments. =item LocalHost => STRING =item LocalService => STRING Hostname and service name for the local address to C to. =item LocalAddr => STRING =item LocalPort => STRING For symmetry with the accessor methods and compatibility with C, these are accepted as synonyms for C and C respectively. =item LocalAddrInfo => ARRAY Alternate form of specifying the local address to C to. This should be an array of the form returned by C. This parameter takes precedence over the C, C, C and C arguments. =item Family => INT The address family to pass to C (e.g. C, C). Normally this will be left undefined, and C will search using any address family supported by the system. =item Type => INT The socket type to pass to C (e.g. C, C). Normally defined by the caller; if left undefined C may attempt to infer the type from the service name. =item Proto => STRING or INT The IP protocol to use for the socket (e.g. C<'tcp'>, C, C<'udp'>,C). Normally this will be left undefined, and either C or the kernel will choose an appropriate value. May be given either in string name or numeric form. =item GetAddrInfoFlags => INT More flags to pass to the C function. If not supplied, a default of C will be used. These flags will be combined with C if the C argument is given. For more information see the documentation about C in the L module. =item Listen => INT If defined, puts the socket into listening mode where new connections can be accepted using the C method. The value given is used as the C queue size. =item ReuseAddr => BOOL If true, set the C sockopt =item ReusePort => BOOL If true, set the C sockopt (not all OSes implement this sockopt) =item Broadcast => BOOL If true, set the C sockopt =item V6Only => BOOL If defined, set the C sockopt when creating C sockets to the given value. If true, a listening-mode socket will only listen on the C addresses; if false it will also accept connections from C addresses. If not defined, the socket option will not be changed, and default value set by the operating system will apply. For repeatable behaviour across platforms it is recommended this value always be defined for listening-mode sockets. Note that not all platforms support disabling this option. Some, at least OpenBSD and MirBSD, will fail with C if you attempt to disable it. To determine whether it is possible to disable, you may use the class method if( IO::Socket::IP->CAN_DISABLE_V6ONLY ) { ... } else { ... } If your platform does not support disabling this option but you still want to listen for both C and C connections you will have to create two listening sockets, one bound to each protocol. =item Timeout This C-style argument is not currently supported. See the C INCOMPATIBILITES section below. =item MultiHomed This C-style argument is ignored, except if it is defined but false. See the C INCOMPATIBILITES section below. However, the behaviour it enables is always performed by C. =item Blocking => BOOL If defined but false, the socket will be set to non-blocking mode. Otherwise it will default to blocking mode. See the NON-BLOCKING section below for more detail. =back If neither C nor C hints are provided, a default of C and C respectively will be set, to maintain compatibility with C. Other named arguments that are not recognised are ignored. If the constructor fails, it will set C<$@> to an appropriate error message; this may be from C<$!> or it may be some other string; not every failure necessarily has an associated C value. =head2 $sock = IO::Socket::IP->new( $peeraddr ) As a special case, if the constructor is passed a single argument (as opposed to an even-sized list of key/value pairs), it is taken to be the value of the C parameter. This is parsed in the same way, according to the behaviour given in the C AND C PARSING section below. =cut sub new { my $class = shift; my %arg = (@_ == 1) ? (PeerHost => $_[0]) : @_; return $class->SUPER::new(%arg); } # IO::Socket may call this one; neaten up the arguments from IO::Socket::INET # before calling our real _configure method sub configure { my $self = shift; my ( $arg ) = @_; $arg->{PeerHost} = delete $arg->{PeerAddr} if exists $arg->{PeerAddr} && !exists $arg->{PeerHost}; $arg->{PeerService} = delete $arg->{PeerPort} if exists $arg->{PeerPort} && !exists $arg->{PeerService}; $arg->{LocalHost} = delete $arg->{LocalAddr} if exists $arg->{LocalAddr} && !exists $arg->{LocalHost}; $arg->{LocalService} = delete $arg->{LocalPort} if exists $arg->{LocalPort} && !exists $arg->{LocalService}; for my $type (qw(Peer Local)) { my $host = $type . 'Host'; my $service = $type . 'Service'; if( defined $arg->{$host} ) { ( $arg->{$host}, my $s ) = $self->split_addr( $arg->{$host} ); # IO::Socket::INET compat - *Host parsed port always takes precedence $arg->{$service} = $s if defined $s; } } $self->_configure( $arg ); } sub _configure { my $self = shift; my ( $arg ) = @_; my %hints; my @localinfos; my @peerinfos; if( defined $arg->{GetAddrInfoFlags} ) { $hints{flags} = $arg->{GetAddrInfoFlags}; } else { $hints{flags} = $AI_ADDRCONFIG; } if( defined( my $family = $arg->{Family} ) ) { $hints{family} = $family; } if( defined( my $type = $arg->{Type} ) ) { $hints{socktype} = $type; } if( defined( my $proto = $arg->{Proto} ) ) { unless( $proto =~ m/^\d+$/ ) { my $protonum = getprotobyname( $proto ); defined $protonum or croak "Unrecognised protocol $proto"; $proto = $protonum; } $hints{protocol} = $proto; } # To maintain compatibility with IO::Socket::INET, imply a default of # SOCK_STREAM + IPPROTO_TCP if neither hint is given if( !defined $hints{socktype} and !defined $hints{protocol} ) { $hints{socktype} = SOCK_STREAM; $hints{protocol} = IPPROTO_TCP; } # Some OSes (NetBSD) don't seem to like just a protocol hint without a # socktype hint as well. We'll set a couple of common ones if( !defined $hints{socktype} and defined $hints{protocol} ) { $hints{socktype} = SOCK_STREAM if $hints{protocol} == IPPROTO_TCP; $hints{socktype} = SOCK_DGRAM if $hints{protocol} == IPPROTO_UDP; } if( my $info = $arg->{LocalAddrInfo} ) { ref $info eq "ARRAY" or croak "Expected 'LocalAddrInfo' to be an ARRAY ref"; @localinfos = @$info; } elsif( defined $arg->{LocalHost} or defined $arg->{LocalService} ) { # Either may be undef my $host = $arg->{LocalHost}; my $service = $arg->{LocalService}; local $1; # Placate a taint-related bug; [perl #67962] defined $service and $service =~ s/\((\d+)\)$// and my $fallback_port = $1; my %localhints = %hints; $localhints{flags} |= AI_PASSIVE; ( my $err, @localinfos ) = getaddrinfo( $host, $service, \%localhints ); if( $err and defined $fallback_port ) { ( $err, @localinfos ) = getaddrinfo( $host, $fallback_port, \%localhints ); } if( $err ) { $@ = "$err"; $! = EINVAL; return; } } if( my $info = $arg->{PeerAddrInfo} ) { ref $info eq "ARRAY" or croak "Expected 'PeerAddrInfo' to be an ARRAY ref"; @peerinfos = @$info; } elsif( defined $arg->{PeerHost} or defined $arg->{PeerService} ) { defined( my $host = $arg->{PeerHost} ) or croak "Expected 'PeerHost'"; defined( my $service = $arg->{PeerService} ) or croak "Expected 'PeerService'"; local $1; # Placate a taint-related bug; [perl #67962] defined $service and $service =~ s/\((\d+)\)$// and my $fallback_port = $1; ( my $err, @peerinfos ) = getaddrinfo( $host, $service, \%hints ); if( $err and defined $fallback_port ) { ( $err, @peerinfos ) = getaddrinfo( $host, $fallback_port, \%hints ); } if( $err ) { $@ = "$err"; $! = EINVAL; return; } } my @sockopts_enabled; push @sockopts_enabled, SO_REUSEADDR if $arg->{ReuseAddr}; push @sockopts_enabled, SO_REUSEPORT if $arg->{ReusePort}; push @sockopts_enabled, SO_BROADCAST if $arg->{Broadcast}; my $listenqueue = $arg->{Listen}; croak "Cannot Listen with a PeerHost" if defined $listenqueue and @peerinfos; my $blocking = $arg->{Blocking}; defined $blocking or $blocking = 1; my $v6only = $arg->{V6Only}; # IO::Socket::INET defines this key. IO::Socket::IP always implements the # behaviour it requests, so we can ignore it, unless the caller is for some # reason asking to disable it. if( defined $arg->{MultiHomed} and !$arg->{MultiHomed} ) { croak "Cannot disable the MultiHomed parameter"; } my @infos; foreach my $local ( @localinfos ? @localinfos : {} ) { foreach my $peer ( @peerinfos ? @peerinfos : {} ) { next if defined $local->{family} and defined $peer->{family} and $local->{family} != $peer->{family}; next if defined $local->{socktype} and defined $peer->{socktype} and $local->{socktype} != $peer->{socktype}; next if defined $local->{protocol} and defined $peer->{protocol} and $local->{protocol} != $peer->{protocol}; my $family = $local->{family} || $peer->{family} or next; my $socktype = $local->{socktype} || $peer->{socktype} or next; my $protocol = $local->{protocol} || $peer->{protocol} || 0; push @infos, { family => $family, socktype => $socktype, protocol => $protocol, localaddr => $local->{addr}, peeraddr => $peer->{addr}, }; } } if( !@infos ) { # If there was a Family hint then create a plain unbound, unconnected socket # If there wasn't, use getaddrinfo()'s AI_ADDRCONFIG side-effect to guess a # suitable family first. if( !defined $hints{family} ) { my ( $err, $addrinfo ) = getaddrinfo( "", "0", \%hints ); if( $err ) { $@ = "$err"; $! = EINVAL; return; } $hints{family} = $addrinfo->{family}; } @infos = ( { family => $hints{family}, socktype => $hints{socktype}, protocol => $hints{protocol}, } ); } # In the nonblocking case, caller will be calling ->setup multiple times. # Store configuration in the object for the ->setup method # Yes, these are messy. Sorry, I can't help that... ${*$self}{io_socket_ip_infos} = \@infos; ${*$self}{io_socket_ip_idx} = -1; ${*$self}{io_socket_ip_sockopts} = \@sockopts_enabled; ${*$self}{io_socket_ip_v6only} = $v6only; ${*$self}{io_socket_ip_listenqueue} = $listenqueue; ${*$self}{io_socket_ip_blocking} = $blocking; ${*$self}{io_socket_ip_errors} = [ undef, undef, undef ]; # ->setup is allowed to return false in nonblocking mode $self->setup or !$blocking or return undef; return $self; } sub setup { my $self = shift; while(1) { ${*$self}{io_socket_ip_idx}++; last if ${*$self}{io_socket_ip_idx} >= @{ ${*$self}{io_socket_ip_infos} }; my $info = ${*$self}{io_socket_ip_infos}->[${*$self}{io_socket_ip_idx}]; $self->socket( @{$info}{qw( family socktype protocol )} ) or ( ${*$self}{io_socket_ip_errors}[2] = $!, next ); $self->blocking( 0 ) unless ${*$self}{io_socket_ip_blocking}; foreach my $sockopt ( @{ ${*$self}{io_socket_ip_sockopts} } ) { $self->setsockopt( SOL_SOCKET, $sockopt, pack "i", 1 ) or ( $@ = "$!", return undef ); } if( defined ${*$self}{io_socket_ip_v6only} and defined $AF_INET6 and $info->{family} == $AF_INET6 ) { my $v6only = ${*$self}{io_socket_ip_v6only}; $self->setsockopt( IPPROTO_IPV6, IPV6_V6ONLY, pack "i", $v6only ) or ( $@ = "$!", return undef ); } if( defined( my $addr = $info->{localaddr} ) ) { $self->bind( $addr ) or ( ${*$self}{io_socket_ip_errors}[1] = $!, next ); } if( defined( my $listenqueue = ${*$self}{io_socket_ip_listenqueue} ) ) { $self->listen( $listenqueue ) or ( $@ = "$!", return undef ); } if( defined( my $addr = $info->{peeraddr} ) ) { if( $self->connect( $addr ) ) { $! = 0; return 1; } if( $! == EINPROGRESS or HAVE_MSWIN32 && $! == Errno::EWOULDBLOCK() ) { ${*$self}{io_socket_ip_connect_in_progress} = 1; return 0; } ${*$self}{io_socket_ip_errors}[0] = $!; next; } return 1; } # Pick the most appropriate error, stringified $! = ( grep defined, @{ ${*$self}{io_socket_ip_errors}} )[0]; $@ = "$!"; return undef; } sub connect { my $self = shift; # It seems that IO::Socket hides EINPROGRESS errors, making them look like # a success. This is annoying here. # Instead of putting up with its frankly-irritating intentional breakage of # useful APIs I'm just going to end-run around it and call CORE::connect() # directly return CORE::connect( $self, $_[0] ) if @_; return 1 if !${*$self}{io_socket_ip_connect_in_progress}; # See if a connect attempt has just failed with an error if( my $errno = $self->getsockopt( SOL_SOCKET, SO_ERROR ) ) { delete ${*$self}{io_socket_ip_connect_in_progress}; ${*$self}{io_socket_ip_errors}[0] = $! = $errno; return $self->setup; } # No error, so either connect is still in progress, or has completed # successfully. We can tell by trying to connect() again; either it will # succeed or we'll get EISCONN (connected successfully), or EALREADY # (still in progress). This even works on MSWin32. my $addr = ${*$self}{io_socket_ip_infos}[${*$self}{io_socket_ip_idx}]{peeraddr}; if( $self->connect( $addr ) or $! == EISCONN ) { delete ${*$self}{io_socket_ip_connect_in_progress}; $! = 0; return 1; } else { $! = EINPROGRESS; return 0; } } sub connected { my $self = shift; return defined $self->fileno && !${*$self}{io_socket_ip_connect_in_progress} && defined getpeername( $self ); # ->peername caches, we need to detect disconnection } =head1 METHODS As well as the following methods, this class inherits all the methods in L and L. =cut sub _get_host_service { my $self = shift; my ( $addr, $flags, $xflags ) = @_; $flags |= NI_DGRAM if $self->socktype == SOCK_DGRAM; my ( $err, $host, $service ) = getnameinfo( $addr, $flags, $xflags || 0 ); croak "getnameinfo - $err" if $err; return ( $host, $service ); } sub _unpack_sockaddr { my ( $addr ) = @_; my $family = sockaddr_family $addr; if( $family == AF_INET ) { return ( Socket::unpack_sockaddr_in( $addr ) )[1]; } elsif( defined $AF_INET6 and $family == $AF_INET6 ) { return ( Socket::unpack_sockaddr_in6( $addr ) )[1]; } else { croak "Unrecognised address family $family"; } } =head2 ( $host, $service ) = $sock->sockhost_service( $numeric ) Returns the hostname and service name of the local address (that is, the socket address given by the C method). If C<$numeric> is true, these will be given in numeric form rather than being resolved into names. The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call C only once. =cut sub sockhost_service { my $self = shift; my ( $numeric ) = @_; $self->_get_host_service( $self->sockname, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 ); } =head2 $addr = $sock->sockhost Return the numeric form of the local address as a textual representation =head2 $port = $sock->sockport Return the numeric form of the local port number =head2 $host = $sock->sockhostname Return the resolved name of the local address =head2 $service = $sock->sockservice Return the resolved name of the local port number =cut sub sockhost { my $self = shift; ( $self->_get_host_service( $self->sockname, NI_NUMERICHOST, NIx_NOSERV ) )[0] } sub sockport { my $self = shift; ( $self->_get_host_service( $self->sockname, NI_NUMERICSERV, NIx_NOHOST ) )[1] } sub sockhostname { my $self = shift; ( $self->_get_host_service( $self->sockname, 0, NIx_NOSERV ) )[0] } sub sockservice { my $self = shift; ( $self->_get_host_service( $self->sockname, 0, NIx_NOHOST ) )[1] } =head2 $addr = $sock->sockaddr Return the local address as a binary octet string =cut sub sockaddr { my $self = shift; _unpack_sockaddr $self->sockname } =head2 ( $host, $service ) = $sock->peerhost_service( $numeric ) Returns the hostname and service name of the peer address (that is, the socket address given by the C method), similar to the C method. The following four convenience wrappers may be used to obtain one of the two values returned here. If both host and service names are required, this method is preferable to the following wrappers, because it will call C only once. =cut sub peerhost_service { my $self = shift; my ( $numeric ) = @_; $self->_get_host_service( $self->peername, $numeric ? NI_NUMERICHOST|NI_NUMERICSERV : 0 ); } =head2 $addr = $sock->peerhost Return the numeric form of the peer address as a textual representation =head2 $port = $sock->peerport Return the numeric form of the peer port number =head2 $host = $sock->peerhostname Return the resolved name of the peer address =head2 $service = $sock->peerservice Return the resolved name of the peer port number =cut sub peerhost { my $self = shift; ( $self->_get_host_service( $self->peername, NI_NUMERICHOST, NIx_NOSERV ) )[0] } sub peerport { my $self = shift; ( $self->_get_host_service( $self->peername, NI_NUMERICSERV, NIx_NOHOST ) )[1] } sub peerhostname { my $self = shift; ( $self->_get_host_service( $self->peername, 0, NIx_NOSERV ) )[0] } sub peerservice { my $self = shift; ( $self->_get_host_service( $self->peername, 0, NIx_NOHOST ) )[1] } =head2 $addr = $peer->peeraddr Return the peer address as a binary octet string =cut sub peeraddr { my $self = shift; _unpack_sockaddr $self->peername } # This unbelievably dodgy hack works around the bug that IO::Socket doesn't do # it # https://rt.cpan.org/Ticket/Display.html?id=61577 sub accept { my $self = shift; my ( $new, $peer ) = $self->SUPER::accept( @_ ) or return; ${*$new}{$_} = ${*$self}{$_} for qw( io_socket_domain io_socket_type io_socket_proto ); return wantarray ? ( $new, $peer ) : $new; } # This second unbelievably dodgy hack guarantees that $self->fileno doesn't # change, which is useful during nonblocking connect sub socket { my $self = shift; return $self->SUPER::socket(@_) if not defined $self->fileno; # I hate core prototypes sometimes... CORE::socket( my $tmph, $_[0], $_[1], $_[2] ) or return undef; dup2( $tmph->fileno, $self->fileno ) or die "Unable to dup2 $tmph onto $self - $!"; } # Versions of IO::Socket before 1.35 may leave socktype undef if from, say, an # ->fdopen call. In this case we'll apply a fix BEGIN { if( $IO::Socket::VERSION < 1.35 ) { *socktype = sub { my $self = shift; my $type = $self->SUPER::socktype; if( !defined $type ) { $type = $self->sockopt( Socket::SO_TYPE() ); } return $type; }; } } =head2 $inet = $sock->as_inet Returns a new L instance wrapping the same filehandle. This may be useful in cases where it is required, for backward-compatibility, to have a real object of C type instead of C. The new object will wrap the same underlying socket filehandle as the original, so care should be taken not to continue to use both objects concurrently. Ideally the original C<$sock> should be discarded after this method is called. This method checks that the socket domain is C and will throw an exception if it isn't. =cut sub as_inet { my $self = shift; croak "Cannot downgrade a non-PF_INET socket to IO::Socket::INET" unless $self->sockdomain == AF_INET; return IO::Socket::INET->new_from_fd( $self->fileno, "r+" ); } =head1 NON-BLOCKING If the constructor is passed a defined but false value for the C argument then the socket is put into non-blocking mode. When in non-blocking mode, the socket will not be set up by the time the constructor returns, because the underlying C syscall would otherwise have to block. The non-blocking behaviour is an extension of the C API, unique to C, because the former does not support multi-homed non-blocking connect. When using non-blocking mode, the caller must repeatedly check for writeability on the filehandle (for instance using C