@@ -129,6 +129,8 @@ public function query(Query $query)
129129 }
130130
131131 // UDP connections are instant, so try connection without a loop or timeout
132+ $ errno = 0 ;
133+ $ errstr = '' ;
132134 $ socket = @\stream_socket_client ($ this ->nameserver , $ errno , $ errstr , 0 );
133135 if ($ socket === false ) {
134136 return \React \Promise \reject (new \RuntimeException (
@@ -139,18 +141,25 @@ public function query(Query $query)
139141
140142 // set socket to non-blocking and immediately try to send (fill write buffer)
141143 \stream_set_blocking ($ socket , false );
142- $ written = @\fwrite ($ socket , $ queryData );
143144
144- if ($ written !== \strlen ( $ queryData ) ) {
145+ \set_error_handler ( function ($ _ , $ error ) use (& $ errno , & $ errstr ) {
145146 // Write may potentially fail, but most common errors are already caught by connection check above.
146147 // Among others, macOS is known to report here when trying to send to broadcast address.
147148 // This can also be reproduced by writing data exceeding `stream_set_chunk_size()` to a server refusing UDP data.
148149 // fwrite(): send of 8192 bytes failed with errno=111 Connection refused
149- $ error = \error_get_last ();
150- \preg_match ('/errno=(\d+) (.+)/ ' , $ error ['message ' ], $ m );
150+ \preg_match ('/errno=(\d+) (.+)/ ' , $ error , $ m );
151+ $ errno = isset ($ m [1 ]) ? (int ) $ m [1 ] : 0 ;
152+ $ errstr = isset ($ m [2 ]) ? $ m [2 ] : $ error ;
153+ });
154+
155+ $ written = \fwrite ($ socket , $ queryData );
156+
157+ \restore_error_handler ();
158+
159+ if ($ written !== \strlen ($ queryData )) {
151160 return \React \Promise \reject (new \RuntimeException (
152- 'DNS query for ' . $ query ->describe () . ' failed: Unable to send query to DNS server ' . $ this ->nameserver . ' ( ' . ( isset ( $ m [ 2 ]) ? $ m [ 2 ] : $ error [ ' message ' ]) . ') ' ,
153- isset ( $ m [ 1 ]) ? ( int ) $ m [ 1 ] : 0
161+ 'DNS query for ' . $ query ->describe () . ' failed: Unable to send query to DNS server ' . $ this ->nameserver . ' ( ' . $ errstr . ') ' ,
162+ $ errno
154163 ));
155164 }
156165
0 commit comments