in reply to Re: Hex value of Perl file handle to uniquely identify
in thread Hex value of Perl file handle to uniquely identify

The value of the internal file handle should suffice. To give some background, I am writing a simple mock tcp server, using IO::Socket::INET and IO::Select, to use in system testing. It is not finished yet, but as a minimum I'd like to at least display the socket ids in a trace so I can tell which client is sending what. Here are some (incomplete) code snippets to give you a feel:

my $listener = IO::Socket::INET->new( LocalPort => $port, Proto => 'tcp', Listen => 5, ReuseAddr => 1, ) or die "error: IO::Socket::INET: $@"; my $selector = IO::Select->new($listener); while ( my @ready = $selector->can_read() ) { for my $client (@ready) { if ( $client == $listener ) { my $new_conn = $listener->accept(); $selector->add($new_conn); my $fh_hex = sprintf '0x%x', $new_conn; print "Accepted new connection ($fh_hex)\n"; # ... sub recv_client { my $client = shift; my $fh_hex = sprintf '0x%x', $client; print "Recv from client ($fh_hex):\n"; # ... display data received ... }

Update: Thanks to BrowserUk's excellent tip I am now using:

my $fh_hex = sprintf '0x%x', $new_conn; my $peerhost = $new_conn->peerhost(); my $peerport = $new_conn->peerport(); my $peeraddr = $new_conn->peeraddr(); my $peerhostfull = gethostbyaddr($peeraddr, AF_INET) || "Cannot resolv +e"; print "Accepted new connection $fh_hex ($peerhost:$peerport,host=$peer +hostfull)\n";
which is much better.

Replies are listed 'Best First'.
Re^3: Hex value of Perl file handle to uniquely identify
by BrowserUk (Patriarch) on Apr 09, 2016 at 07:42 UTC

    Be aware that handles do get reused. Once a client disconnects, the next connect might reuse that handle.

    For uniqueness, you might consider combining the output from IO::Socket's PeerHost() and PeerPort() methods: xxx.xxx.xxx.xxx:nnnn.

    Also, I don't see a lot of value in sprintfing the handle, over the default stringification 'GLOB(0xHHHHHH)"?


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re^3: Hex value of Perl file handle to uniquely identify
by Anonymous Monk on Apr 09, 2016 at 16:47 UTC
    $unique{$new_conn}++; $unique_id = "$client $unique{$client}";

    glob plus counter per glob