in reply to Re: Detecting a port "in use" on localhost:$port
in thread Detecting a port "in use" on localhost:$port

Sorry, I don't seem to have the lingo down on this. An example will make things more clear.

Say I'd like to run Apache configured to answer on port 8888. OK, let's go check to see if any other program is "using" 8888. Might be a gopher server, telnet server, etc. I would like to detect if there is a server answering requests on 8888 already.

-------------------------------------
Nothing is too wonderful to be true
-- Michael Faraday

Replies are listed 'Best First'.
Re^3: Detecting a port "in use" on localhost:$port
by ikegami (Patriarch) on Apr 22, 2009 at 01:11 UTC

    Just bind to the port. Trying to connect to the socket is slower and less reliable.

    use strict; use warnings; use Errno qw( EADDRINUSE ); use Socket qw( PF_INET SOCK_STREAM INADDR_ANY sockaddr_in ); sub port_available { my $family = PF_INET; my $type = SOCK_STREAM; my $proto = getprotobyname('tcp') or die "getprotobyname: $!"; my $host = INADDR_ANY; # Use inet_aton for a specific interface my $port = '8888'; socket(my $sock, $family, $type, $proto) or die "socket: $!"; my $name = sockaddr_in($port, $host) or die "sockaddr_in: $!"; bind($sock, $name) and return 1; $! == EADDRINUSE and return 0; die "bind: $!"; } print port_available() ? "available\n" : "in use\n";

    Tested on linux and Windows.

    I would still like to know how this is useful to you.