dymk
dymk

Reputation: 897

WinSock's send() always returning 0 bytes sent

I've been experiencing a problem with the Winsock2's function send(). No matter what data I provide it, the send() function always returns 0; eg 0 bytes sent, and no errors. I've google searched for a while now, but have yet to find a solution. I've checked that the data being send is correctly formatted, and I'm passing it a valid socket.

Here is a snippet of the code which the bug resides in (I would think at least):

    //Send HTTP header to server
#define MAX_HEADER_LEN 512

#ifdef UNICODE

    char* cpHost = (char*)malloc(sizeof(char) * (_tcslen(cpServer)+1));
    wcstombs(cpHost, cpServer, _tcslen(cpServer));
    cpHost[_tcslen(cpServer)] = '\0';

#else
    char* cpHost = cpServer;
#endif

    char cpHeader[MAX_HEADER_LEN];
    sprintf(cpHeader, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", "/", cpHost);

#ifdef UNICODE
    free(cpHost);
#endif

    //Send the HTTP request to the sever
    int iSent;
    if(iSent = send(servSocket, cpHeader, strlen(cpHeader), 0) == SOCKET_ERROR)
    {
        _tprintf(TEXT("Error sending header to server: %d\n"), WSAGetLastError());
        WSACleanup();
        return 2;
    }

    _tprintf(TEXT("Sent '%d' bytes\n"), iSent);

    return 0;

Any ideas what is causing this behavior?

Here is the full source of the file (pardon all the bad coding habits): http://pastebin.com/URsaFz0Q

Thanks for your help, --Dylan

Upvotes: 0

Views: 1151

Answers (1)

David Schwartz
David Schwartz

Reputation: 182819

Your code sets iSent to zero on success. On success, send doesn't return SOCKET_ERROR, so send(...)==SOCKET_ERROR is false. False is zero in C.

Change:

int iSent;
if(iSent = send(servSocket, cpHeader, strlen(cpHeader), 0) == SOCKET_ERROR)

To:

int iSent = send(servSocket, cpHeader, strlen(cpHeader), 0);
if(iSent == SOCKET_ERROR)

Or:

int iSent;
if( (iSent = send(servSocket, cpHeader, strlen(cpHeader), 0)) == SOCKET_ERROR)

Upvotes: 4

Related Questions