Search code examples
c++socketssendto

UDP Socket error 10049


I have a UDP server socket which can receive datagrams from clients, but is not able to send a reply back to any of them.

This is the code I use to send the buffer:

    SOCKADDR_IN addr;
    memset((char*)&addr, 0, sizeof(addr));

    const char* ip = "127.0.0.1";
    u_short port = 8888 // IP of the client to which the buffer is going to

    if (inet_pton(AF_INET, ip, &addr) == 1)
    {
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);

        sendto(s, buffer, UDP_PACKET_SIZE, NULL, (SOCKADDR *)&addr, addrlen);
    }

sendto() returns -1 and GetLastError() says 10049 which means the address is not available. I'm sending and receiving the buffer on localhost.


Solution

  • You're passing a pointer to the SOCKADDR_IN structure as third argument to inet_pton, but if you follow the link to the MSDN reference of the function you will see that it wants an IN_ADDR structure.

    The SOCKADDR_IN structure has such a member, but it's not the first member in the structure, which is why you get the error; You write the address to the wrong place in the structure and the address you try to send to is not what you think it is.

    The correct call would be e.g.

    inet_pton(AF_INET, ip, &addr.sin_addr)