@@ -172,41 +172,47 @@ - (BOOL)socketIsAvailableForHost:(NSString *)host port:(int)port timeout:(int)ti
172
172
addr.sin_port = htons (port);
173
173
inet_pton (AF_INET, [host UTF8String ], &addr.sin_addr );
174
174
175
+ // Start the connection
175
176
int result = connect (sock, (struct sockaddr *)&addr, sizeof (addr));
176
177
178
+ // If connect() returns 0, the connection was established immediately
177
179
if (result == 0 ) {
178
180
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) {
181
186
close (sock);
182
- return NO ; // Connection failed immediately for non-timeout reasons
187
+ return NO ; // Connection failed for reasons other than timeout
183
188
}
184
189
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()
186
191
fd_set writefds;
187
192
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
190
195
191
196
FD_ZERO (&writefds);
192
197
FD_SET (sock, &writefds);
193
198
199
+ // Wait for the socket to be writable, indicating a successful connection
194
200
int selectResult = select (sock + 1 , NULL , &writefds, NULL , &tv);
195
- close (sock);
196
-
197
201
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
205
209
}
206
- return NO ; // Connection failed or timed out
207
210
}
208
- }
209
211
212
+ // Connection failed or timed out
213
+ close (sock);
214
+ return NO ;
215
+ }
210
216
211
217
RCT_EXPORT_METHOD (cancelDiscovering) {
212
218
isDiscovering = NO ; // Set flag to NO to cancel discovery
0 commit comments