Question

I'm setting up reporting on my PHP script with etsy's open source statsd library. I'm basing my connection on their given example, but I'm running into an issue where it seems like fsockopen is ignoring try/catch and is printing its errors.

Everything works grand when the statsd server is up and running - but if it's down or the php script cannot connect to it:

Warning: fsockopen(): php_network_getaddresses: getaddrinfo failed: 
Name or service not known

I even attempted adding @ in front of fsockopen, but no dice. It also seems to be completely ignoring the timeout setting, as it takes about 20 seconds to return the error:

        try {
            $host = 'stats.thisserverisdown.com';
            $port = '8125';
            if ( $fp = @fsockopen("udp://$host", $port, $errno, $errstr, 1) ) {
                if (!(get_resource_type($fp) == 'stream')) { return false; }
                stream_set_timeout($fp,1);
                stream_set_blocking($fp,false);
                foreach ($sampledData as $stat => $value) {
                    @fwrite($fp, "$stat:$value");
                }
                @fclose($fp);
            }
            return true;
        } catch (Exception $e) {
            return false;
        }
Was it helpful?

Solution

fsockopen is not throwing the error. Because fsockopen has to resolve the hostname you provided, it calls getaddinfo(), which is failing.

Try supplying an IP address, or:

fsockopen( @"udp://$host", ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top