[C++]UDP Socket Errors

Results 1 to 2 of 2
  1. #1
    Elite Member BluStudio is offline
    Member +Rank
    Jun 2008 Join Date
    133Posts

    [C++]UDP Socket Errors

    Why "recieved_bytes" is always smaller than 0?
    Code:
    #include <iostream>
    #include <windows.h>
    #pragma comment(lib, "wsock32.lib")
    void main()
    {
        WSADATA WsaData;
        if(WSAStartup(MAKEWORD(2,2),&WsaData) != NO_ERROR)
        {
            return;
        }
        int handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if(handle <= 0)
        {
            return;
        }
        sockaddr_in address;
        address.sin_family = AF_INET;
        address.sin_addr.s_addr = INADDR_ANY;
        address.sin_port = htons((unsigned short)"44405");
        if(bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in)) < 0)
        {
            return;
        }
        DWORD nonBlocking = 1;
        if(ioctlsocket(handle, FIONBIO, &nonBlocking) != 0)
        {
            return;
        }
        while(true)
        {
            unsigned char packet_data[256];
            unsigned int maximum_packet_size = sizeof(packet_data);
            typedef int socklen_t;
            sockaddr_in from;
            socklen_t fromLength = sizeof(from);
            int received_bytes = recvfrom(handle, (char*)packet_data, maximum_packet_size,  0, (sockaddr*)&from, &fromLength);
            if(received_bytes < 0)
            {
                break;
            }
            unsigned int from_address = ntohl( from.sin_addr.s_addr );
            unsigned int from_port = ntohs( from.sin_port );
        }
        WSACleanup();
    }


  2. #2
    Ginger by design. jMerliN is offline
    Grand MasterRank
    Feb 2007 Join Date
    2,500Posts

    Re: [C++]UDP Socket Errors

    1. Use ws2_32.lib, not wsock2.lib.

    2. http://msdn.microsoft.com/en-us/libr...20(VS.85).aspx

    It only returns an error code that's "less than 0" (btw, your error checking is horribly bad), which is SOCKET_ERROR, which is defined as 0xFFFFFFFF (which is -1). The prescribed action is to call WSAGetLastError, as mentioned in the documentation.

    Also, your code looks like you expect recvfrom to block. It won't, because you're setting FIONBIO to 1, which disables blocking. So you're going to get a WSAEWOULDBLOCK mostly.
    Last edited by jMerliN; 20-09-09 at 07:19 PM.



Advertisement