MCPcopy Create free account
hub / github.com/LUX-Core/lux / ConnectSocketDirectly

Function ConnectSocketDirectly

src/netbase.cpp:404–486  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

402}
403
404bool static ConnectSocketDirectly(const CService& addrConnect, SOCKET& hSocketRet, int nTimeout)
405{
406 hSocketRet = INVALID_SOCKET;
407
408 struct sockaddr_storage sockaddr;
409 socklen_t len = sizeof(sockaddr);
410 if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
411 LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
412 return false;
413 }
414
415 SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
416 if (hSocket == INVALID_SOCKET)
417 return false;
418
419 int set = 1;
420#ifdef SO_NOSIGPIPE
421 // Different way of disabling SIGPIPE on BSD
422 setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
423#endif
424
425//Disable Nagle's algorithm
426#ifdef WIN32
427 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
428#else
429 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
430#endif
431
432 // Set to non-blocking
433 if (!SetSocketNonBlocking(hSocket, true))
434 return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
435
436 if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
437 int nErr = WSAGetLastError();
438 // WSAEINVAL is here because some legacy version of winsock uses it
439 if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
440 struct timeval timeout = MillisToTimeval(nTimeout);
441 fd_set fdset;
442 FD_ZERO(&fdset);
443 FD_SET(hSocket, &fdset);
444 int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
445 if (nRet == 0) {
446 LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
447 CloseSocket(hSocket);
448 return false;
449 }
450 if (nRet == SOCKET_ERROR) {
451 LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
452 CloseSocket(hSocket);
453 return false;
454 }
455 socklen_t nRetSize = sizeof(nRet);
456#ifdef WIN32
457 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
458#else
459 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
460#endif
461 {

Callers 2

ConnectSocketFunction · 0.85
ConnectSocketByNameFunction · 0.85

Calls 7

errorFunction · 0.85
NetworkErrorStringFunction · 0.85
MillisToTimevalFunction · 0.85
LogPrintFunction · 0.85
CloseSocketFunction · 0.85
GetSockAddrMethod · 0.80
ToStringMethod · 0.45

Tested by

no test coverage detected