in reply to Client Server
You can turn the $client_addr received from accept into a human-readable IP address using unpack_sockaddr_in and inet_ntoa (and then echo that back to the client, as sn1987a described in Re: Client Server). That said, Socket is a fairly low-level module; are you sure you don't want something else instead, say IO::Socket?
For instance, here's the server:
#!/usr/bin/perl use warnings; use strict; use IO::Socket; use Socket; # use port 7890 as default my $port = shift || 7890; my $socket = IO::Socket::INET->new( LocalPort => $port, Type => SOCK_STREAM, Reuse => 1, Listen => 10, ) or die "Couldn't create server: $@\n"; while (my $client = $socket->accept()) { my ($port, $iaddr) = unpack_sockaddr_in($client->peername()); $client->send(inet_ntoa($iaddr)); $client->close(); }
And here's the client:
#!/usr/bin/perl use feature qw/say/; use warnings; use strict; use IO::Socket; # initialize host and port my $port = shift || 7890; my $server = "localhost"; # Host IP running the server my $socket = IO::Socket::INET->new( PeerAddr => $server, PeerPort => $port, Proto => "tcp", Type => SOCK_STREAM ) or die "Can't connect to server: $@\n"; while(<$socket>) { say; } close $socket or die "Can't close socket: $!";
Credit where credit is due: all this is pretty much directly copied from The Perl Cookbook, specifically Recipes 17.1 ("Writing a TCP Client"), 17.2 ("Writing a TCP Server") and 17.7 ("Identifying the Other End of a Socket". I really recommend that book, it's very handy.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Client Server
by Anonymous Monk on Jul 09, 2014 at 22:55 UTC | |
|
Re^2: Client Server
by TheVend (Novice) on Jul 15, 2014 at 17:28 UTC | |
by AppleFritter (Vicar) on Jul 15, 2014 at 18:11 UTC | |
by Anonymous Monk on Jul 15, 2014 at 18:30 UTC |