1# You may distribute under the terms of either the GNU General Public License 2# or the Artistic License (the same terms as Perl itself) 3# 4# (C) Paul Evans, 2011 -- leonerd@leonerd.org.uk 5 6package Socket::GetAddrInfo::Strict; 7 8use strict; 9use warnings; 10 11use Carp; 12 13our $VERSION = '0.22'; 14 15use Exporter 'import'; 16our @EXPORT_OK = qw( 17 getaddrinfo 18 getnameinfo 19); 20 21use Socket::GetAddrInfo (); 22 23# Re-export all the AI_*, EAI_* and NI_* constants 24my @constants = @{ $Socket::GetAddrInfo::EXPORT_TAGS{constants} }; 25push @EXPORT_OK, @constants; 26Socket::GetAddrInfo->import( @constants ); 27 28=head1 NAME 29 30C<Socket::GetAddrInfo::Strict> - Provide L<Socket::GetAddrInfo> functions 31which throw exceptions 32 33=head1 SYNOPSIS 34 35 use Socket qw( SOCK_STREAM ); 36 use Socket::GetAddrInfo::Strict qw( getaddrinfo getnameinfo ); 37 use IO::Socket; 38 39 my $sock; 40 41 my %hints = ( socktype => SOCK_STREAM ); 42 my @res = getaddrinfo( "www.google.com", "www", \%hints ); 43 44 while( my $ai = shift @res ) { 45 46 $sock = IO::Socket->new(); 47 $sock->socket( $ai->{family}, $ai->{socktype}, $ai->{protocol} ) or 48 undef $sock, next; 49 50 $sock->connect( $ai->{addr} ) or undef $sock, next; 51 52 last; 53 } 54 55 if( $sock ) { 56 my ( $host, $service ) = getnameinfo( $sock->peername ); 57 print "Connected to $host:$service\n"; 58 } 59 60=head1 DESCRIPTION 61 62L<Socket::GetAddrInfo> provides the functions of C<getaddrinfo> and 63C<getnameinfo>, which return lists whose first element is error value, or 64false indicating no error occured. 65 66This module wraps the functions provided by C<Socket::GetAddrInfo> to check 67this error value, and throw an exception (using C<die>) if an error occured. 68If not, then the remaining values are returned as normal. This can simplify 69the logic of a program which otherwise simply throws its own exception on 70failure anyway. 71 72=cut 73 74=head1 FUNCTIONS 75 76=cut 77 78=head2 @res = getaddrinfo( $host, $service, $hints ) 79 80After a successful lookup, returns the list of address structures, as 81documented in L<Socket::GetAddrInfo>. If the lookup fails, an exception 82containing the string form of the error is thrown instead. 83 84=cut 85 86sub getaddrinfo 87{ 88 my ( $err, @res ) = Socket::GetAddrInfo::getaddrinfo( @_ ); 89 die "$err\n" if $err; 90 return @res; 91} 92 93=head2 ( $host, $service ) = getnameinfo( $addr, $flags, $xflags ) 94 95After a successful lookup, returns the host and service name, as 96documented in L<Socket::GetAddrInfo>. If the lookup fails, an exception 97containing the string form of the error is thrown instead. 98 99=cut 100 101sub getnameinfo 102{ 103 my ( $err, $host, $service ) = Socket::GetAddrInfo::getnameinfo( @_ ); 104 die "$err\n" if $err; 105 return ( $host, $service ); 106} 107 108=head1 AUTHOR 109 110Paul Evans <leonerd@leonerd.org.uk> 111 112=cut 113 1140x55AA; 115