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

How can I detect if a port is in use?

I don't follow. You don't bind to a port, so the system will always assign you one that's not in use.

That means you're probably talking about the port to which you are connecting. What does it being "in use" mean to you? And why is that (rather than whether you can connect to it or not) is relevant?

Replies are listed 'Best First'.
Re^2: Detecting a port "in use" on localhost:$port
by freddo411 (Chaplain) on Apr 21, 2009 at 22:35 UTC
    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

      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.