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.


In reply to Re: Client Server by AppleFritter
in thread Client Server by TheVend

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.