On Tue Mar 12 16:21:07 2013, BBYRD wrote:
Show quoted text> Well, I think of it as a reverse translation of split_addr, and the
> PeerHost/LocalHost params. You can input the host either with "host:port"
> or "host", split it out separately (via split_addr), and get both parts
> all day long.
>
> But, there's nothing available to put them back together again. Given
> that it's not quite as simple as "$host:$port", in the case of IPv6, it
> strikes me that it should be a function within IO::Socket::IP.
Find attached a patch to implement "join_addr", an analogously reverse version of split_addr().
Hopefully this should be useful to get most of what you were after.
--
Paul Evans
=== modified file 'lib/IO/Socket/IP.pm'
--- lib/IO/Socket/IP.pm 2013-04-12 18:53:22 +0000
+++ lib/IO/Socket/IP.pm 2013-04-12 19:17:46 +0000
@@ -964,6 +964,31 @@
return ( $addr, undef );
}
+=head2 $addr = IO::Socket::IP->join_addr( $host, $port )
+
+Utility method that performs the reverse of C<split_addr>, returning a string
+formed by joining the specified host address and port number. The host address
+will be wrapped in C<[]> brackets if required (because it is a raw IPv6
+numeric address).
+
+This can be especially useful when combined with the C<sockhost_service> or
+C<peerhost_service> methods.
+
+ say "Connected to ", IO::Socket::IP->join_addr( $sock->peerhost_service );
+
+=cut
+
+sub join_addr
+{
+ shift;
+ my ( $host, $port ) = @_;
+
+ $host = "[$host]" if $host =~ m/:/;
+
+ return join ":", $host, $port if defined $port;
+ return $host;
+}
+
=head1 C<IO::Socket::INET> INCOMPATIBILITES
=over 4
=== modified file 't/10args.t'
--- t/10args.t 2013-03-11 22:11:46 +0000
+++ t/10args.t 2013-04-12 19:17:46 +0000
@@ -65,6 +65,22 @@
[ "something.else", undef ],
"split_addr something.else" );
+is( IO::Socket::IP->join_addr( "hostname", "http" ),
+ "hostname:http",
+ 'join_addr hostname:http' );
+
+is( IO::Socket::IP->join_addr( "192.0.2.1", 80 ),
+ "192.0.2.1:80",
+ 'join_addr 192.0.2.1:80' );
+
+is( IO::Socket::IP->join_addr( "2001:db8::1", 80 ),
+ "[2001:db8::1]:80",
+ 'join_addr [2001:db8::1]:80' );
+
+is( IO::Socket::IP->join_addr( "something.else", undef ),
+ "something.else",
+ 'join_addr something.else' );
+
arguments_is(@$_) for @tests;
done_testing;