@@ -172,41 +172,47 @@ - (BOOL)socketIsAvailableForHost:(NSString *)host port:(int)port timeout:(int)ti
172172 addr.sin_port = htons (port);
173173 inet_pton (AF_INET, [host UTF8String ], &addr.sin_addr );
174174
175+ // Start the connection
175176 int result = connect (sock, (struct sockaddr *)&addr, sizeof (addr));
176177
178+ // If connect() returns 0, the connection was established immediately
177179 if (result == 0 ) {
178180 close (sock);
179- return YES ; // Connected successfully
180- } else if (errno != EINPROGRESS) {
181+ return YES ; // Port is open and reachable
182+ }
183+
184+ // If connect() returns -1, check if it's due to EINPROGRESS (indicating non-blocking in progress)
185+ if (result < 0 && errno != EINPROGRESS) {
181186 close (sock);
182- return NO ; // Connection failed immediately for non-timeout reasons
187+ return NO ; // Connection failed for reasons other than timeout
183188 }
184189
185- // Use select() to wait for the socket to become writable within the timeout
190+ // Set up the file descriptor set and timeout for select()
186191 fd_set writefds;
187192 struct timeval tv;
188- tv.tv_sec = timeout / 1000 ; // Seconds
189- tv.tv_usec = (timeout % 1000 ) * 1000 ; // Microseconds
193+ tv.tv_sec = timeout / 1000 ; // Convert milliseconds to seconds
194+ tv.tv_usec = (timeout % 1000 ) * 1000 ; // Convert remainder to microseconds
190195
191196 FD_ZERO (&writefds);
192197 FD_SET (sock, &writefds);
193198
199+ // Wait for the socket to be writable, indicating a successful connection
194200 int selectResult = select (sock + 1 , NULL , &writefds, NULL , &tv);
195- close (sock);
196-
197201 if (selectResult > 0 && FD_ISSET (sock, &writefds)) {
198- // The connection attempt was successful
199- return YES ;
200- } else {
201- // Report connection error if listeners are active
202- if (hasListeners ) {
203- NSDictionary *errorInfo = @{ @" ip " : host, @" port " : @(port)} ;
204- [ self sendEventWithName: @" FLD_CONNECTION_ERROR " body: errorInfo];
202+ int so_error;
203+ socklen_t len = sizeof (so_error) ;
204+ getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
205+
206+ if (so_error == 0 ) {
207+ close (sock) ;
208+ return YES ; // Port is open
205209 }
206- return NO ; // Connection failed or timed out
207210 }
208- }
209211
212+ // Connection failed or timed out
213+ close (sock);
214+ return NO ;
215+ }
210216
211217RCT_EXPORT_METHOD (cancelDiscovering) {
212218 isDiscovering = NO ; // Set flag to NO to cancel discovery
0 commit comments