| 266 | } |
| 267 | |
| 268 | inline void |
| 269 | Connector::connect(void) { |
| 270 | struct addrinfo hints, *servinfo, *p; |
| 271 | int rv; |
| 272 | |
| 273 | #ifdef WIN32 |
| 274 | // Initialise Winsock. |
| 275 | WSADATA wsaData; |
| 276 | int startupResult = WSAStartup(MAKEWORD(2, 2), &wsaData); |
| 277 | if (startupResult != 0) { |
| 278 | printf("WSAStartup failed with error: %d\n", startupResult); |
| 279 | } |
| 280 | #endif |
| 281 | |
| 282 | memset(&hints, 0, sizeof hints); |
| 283 | hints.ai_family = AF_UNSPEC; |
| 284 | hints.ai_socktype = SOCK_STREAM; |
| 285 | |
| 286 | if ((rv = getaddrinfo("localhost", std::to_string(port).c_str(), &hints, |
| 287 | &servinfo)) != 0) { |
| 288 | std::cerr << "getaddrinfo: " << gai_strerror(rv) << "\n"; |
| 289 | goto giveup; |
| 290 | } |
| 291 | |
| 292 | // loop through all the results and connect to the first we can |
| 293 | for (p = servinfo; p != nullptr; p = p->ai_next) { |
| 294 | if ((sockfd = static_cast<int>(socket(p->ai_family, p->ai_socktype, p->ai_protocol))) == -1) { |
| 295 | // errno is set here, but we don't examine it. |
| 296 | continue; |
| 297 | } |
| 298 | |
| 299 | if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { |
| 300 | #ifdef WIN32 |
| 301 | closesocket(sockfd); |
| 302 | #else |
| 303 | close(sockfd); |
| 304 | #endif |
| 305 | // errno is set here, but we don't examine it. |
| 306 | continue; |
| 307 | } |
| 308 | |
| 309 | break; |
| 310 | } |
| 311 | |
| 312 | // Connection failed; give up. |
| 313 | if (p == nullptr) { |
| 314 | goto giveup; |
| 315 | } |
| 316 | |
| 317 | freeaddrinfo(servinfo); // all done with this structure |
| 318 | |
| 319 | _connected = true; |
| 320 | |
| 321 | return; |
| 322 | giveup: |
| 323 | _connected = false; |
| 324 | return; |
| 325 |
no test coverage detected