Checking for listening, established, and closed ports (sockets)?

I’ve found a few ways to check for port state but every solution I’ve seen up to this point makes no attempt to distinguish between ports that are established and or closed (for example, the scripts I’ve found and tried will show both “ESTABLISHED” and anything else like “CLOSE_WAIT” or NULL values as simply being closed). I’d write my own approach but I’m not familiar enough with this concept to know where to start.

Is it possible to use something like fsockopen or socket_create, et al, to distinguish between the various states that ports (or sockets) can be in? Uses for something like this are obvious but my own intentions are to create a kind of “heartbeat checker” for determining life of a server connection for various kinds of systems a script might interact with via TCP or otherwise.

For whatever it’s worth, this is where I am right now:

    $host = '999.999.999.999';//IP Address of Host to Scan
    $from = 1;//Starting Port Number
    $to = 100;.//Ending Port Number

    //Uses sockets...
    $socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP);  
    for($port = $from; $port <= $to ; $port++){
        $connection = @socket_connect($socket , $host ,  $port);
        echo '<div id="port_matrix"><p style="margin:0;padding:0">Port ';
        if ($connection){
            echo $port.' open';
            socket_close($socket);
            $socket = socket_create(AF_INET , SOCK_STREAM , SOL_TCP);  
        }else{
            echo $port.' closed';
        }
    }

It works pretty well but it shows ESTABLISHED port connections as being closed and I’m not sure what else I can do within the closed logic section to drill into the states anymore than what’s already been done.

Any insight into this would be appreciated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.