@@ -202,38 +202,56 @@ void WiFiClient::stop()
202202}
203203
204204int WiFiClient::connect (IPAddress ip, uint16_t port)
205+ {
206+ return connect (ip,port,-1 );
207+ }
208+ int WiFiClient::connect (IPAddress ip, uint16_t port, int32_t timeout)
205209{
206210 int sockfd = socket (AF_INET, SOCK_STREAM, 0 );
207211 if (sockfd < 0 ) {
208212 log_e (" socket: %d" , errno);
209213 return 0 ;
210214 }
215+ fcntl ( sockfd, F_SETFL, fcntl ( sockfd, F_GETFL, 0 ) | O_NONBLOCK );
211216
212217 uint32_t ip_addr = ip;
213218 struct sockaddr_in serveraddr;
214219 bzero ((char *) &serveraddr, sizeof (serveraddr));
215220 serveraddr.sin_family = AF_INET;
216221 bcopy ((const void *)(&ip_addr), (void *)&serveraddr.sin_addr .s_addr , 4 );
217222 serveraddr.sin_port = htons (port);
218- int res = lwip_connect_r (sockfd, (struct sockaddr *)&serveraddr, sizeof (serveraddr));
219- if (res < 0 ) {
220- log_e (" lwip_connect_r: %d" , errno);
223+ fd_set fdset;
224+ struct timeval tv;
225+ FD_ZERO (&fdset);
226+ FD_SET (sockfd, &fdset);
227+ tv.tv_sec = 0 ;
228+ tv.tv_usec = timeout * 1000 ;
229+ lwip_connect_r (sockfd, (struct sockaddr *)&serveraddr, sizeof (serveraddr));
230+ int res = select (sockfd + 1 , nullptr , &fdset, nullptr , timeout<0 ? nullptr : &tv);
231+ if (res != 1 )
232+ {
233+ log_e (" select: %d" ,errno);
221234 close (sockfd);
222235 return 0 ;
223236 }
237+ fcntl ( sockfd, F_SETFL, fcntl ( sockfd, F_GETFL, 0 ) & (~O_NONBLOCK) );
224238 clientSocketHandle.reset (new WiFiClientSocketHandle (sockfd));
225239 _rxBuffer.reset (new WiFiClientRxBuffer (sockfd));
226240 _connected = true ;
227241 return 1 ;
228242}
229243
230244int WiFiClient::connect (const char *host, uint16_t port)
245+ {
246+ return connect (host,port,-1 );
247+ }
248+ int WiFiClient::connect (const char *host, uint16_t port, int32_t timeout)
231249{
232250 IPAddress srv ((uint32_t )0 );
233251 if (!WiFiGenericClass::hostByName (host, srv)){
234252 return 0 ;
235253 }
236- return connect (srv, port);
254+ return connect (srv, port, timeout );
237255}
238256
239257int WiFiClient::setSocketOption (int option, char * value, size_t len)
0 commit comments