static SOCKET connect_to_client()

in win32/src/socket_transport_win32.c [116:178]


static SOCKET connect_to_client(const char* hostname, uint16_t port, uint32_t connection_timeout)
{
    SOCKET result;
    // Codes_SOCKET_TRANSPORT_WIN32_09_015: [ socket_transport_connect shall call socket with the params AF_INET, SOCK_STREAM and IPPROTO_TCP. ]
    SOCKET client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (client_socket == INVALID_SOCKET)
    {
        LogLastError("Failure: socket create failure.");
        result = INVALID_SOCKET;
    }
    else
    {
        char port_string[16];
        if (sprintf(port_string, "%u", port) < 0)
        {
            LogError("failed to copy port value %" PRIu16 "", port);
            result = INVALID_SOCKET;
        }
        else
        {
            ADDRINFO addr_hint = { 0 };
            ADDRINFO* addrInfo = NULL;

            addr_hint.ai_family = AF_INET;
            addr_hint.ai_socktype = SOCK_STREAM;
            addr_hint.ai_protocol = 0;
            addr_hint.ai_flags = AI_CANONNAME;

            if (getaddrinfo(hostname, port_string, &addr_hint, &addrInfo) != 0)
            {
                LogLastError("Failure: getaddrinfo(hostname=%s, portString=%s, &addr_hint=%p, &addrInfo=%p)", hostname, port_string, &addr_hint, &addrInfo);
                result = INVALID_SOCKET;
            }
            else
            {
                LogInfo("Connecting to %s:%" PRIu16 " Machine Name: %s, connection timeout: %" PRIu32 "", hostname, port, MU_P_OR_NULL(addrInfo->ai_canonname), connection_timeout);

                u_long iMode = 1;
                if (ioctlsocket(client_socket, FIONBIO, &iMode) != 0)
                {
                    LogLastError("Failure: ioctlsocket failure.");
                    result = INVALID_SOCKET;
                }
                // Codes_SOCKET_TRANSPORT_WIN32_09_016: [ socket_transport_connect shall call connect_to_endpoint with the connection_timeout_ms to connect to the endpoint. ]
                else if (connect_to_endpoint(client_socket, addrInfo, connection_timeout) != 0)
                {
                    LogLastError("Connection failure. Server: %s:%" PRIu16 " Machine Name: %s.", hostname, port, MU_P_OR_NULL(addrInfo->ai_canonname));
                    result = INVALID_SOCKET;
                }
                else
                {
                    freeaddrinfo(addrInfo);
                    result = client_socket;
                    goto all_ok;
                }
                freeaddrinfo(addrInfo);
            }
        }
        closesocket(client_socket);
    }
all_ok:
    return result;
}