motzi has asked for the wisdom of the Perl Monks concerning the following question:

Hello, i writing threaded program which uses sockets in threads.
In every thread, name of socket is given this way:
sub dbconnect { $mysocket = int rand 100; # (don't tell to use a bigger number please) socket($mysocket, PF_INET, SOCK_STREAM, getprotobyname 'tcp'); # ... }
So, in every thread i want to check if $mysocket is not a socket already before to create a new one. What method can i use?

Thank you.

Replies are listed 'Best First'.
Re: Detect socket
by ikegami (Patriarch) on Apr 21, 2010 at 20:58 UTC
    Won't socket use the first available file descriptor?
    sub dbconnect { socket(my $mysocket, PF_INET, SOCK_STREAM, getprotobyname('tcp')) or die("socket: $!"); fileno($mysocket) >= 100 or die("No available file descriptors below 100\n"); # ... }

    Update: Here's a test that checks if the above works:

    use strict; use warnings; use Socket; my @handles; for (0..9) { open($handles[$_], '<', $0) or die; print("$_: ", fileno($handles[$_]), "\n"); } print("--\n"); close($handles[5]); socket(my $mysocket, PF_INET, SOCK_STREAM, getprotobyname('tcp')) or d +ie; print(fileno($mysocket), "\n");

    Works on my system:

    0: 3 1: 4 2: 6 3: 8 4: 9 5: 10 6: 11 7: 12 8: 13 9: 14 -- 10
      Thanks, but i was wondering if there any method to check if some number is a socket descriptor, instead of working with range of numbers;

      Upd:
      Your updated part of post is very good method, thanks, it's very helpful! Would be nice if there are some more methods.
        There might be, but I don't know it since it's not something one needs to do. Sounds like an XY problem.
        huh? My update just checks if socket uses the first available file descriptor. It doesn't check if some number is a socket descriptor. It doesn't even check if some number is any kind of valid file descriptor.
        That's like wondering if a certain address contains a file-descriptor. You might be able to make the determination, but why would you want to?
Re: Detect socket
by BrowserUk (Patriarch) on Apr 21, 2010 at 23:12 UTC

    You could try calling  getsockopt( $mysocket, getprotobyname( 'tcp' ), TCP_NODELAY ).

    On my OS I get an error that tells me if the file descriptor provided is not a socket:

    getsockopt( STDOUT, getprotobyname( 'tcp' ), TCP_NODELAY ) or warn "?$! : $^E";; ?Unknown error : An operation was attempted on something that is not +a socket

    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".
    In the absence of evidence, opinion is indistinguishable from prejudice.