A
A
andrkkk2020-04-15 11:09:45
C++ / C#
andrkkk, 2020-04-15 11:09:45

How to solve the problem with receiving messages from the client in winsock using UDP?

I deal with winsock, in particular with the udp protocol. When accepting / waiting for a message, an error occurs, although the code is almost all from the microsoft documentation.
recvfrom throws an error with code 10057. It seems to be related to the socket, although socket and bind are successful.
Server code:

#include <iostream>
#pragma comment(lib, "ws2_32.lib")
#include <WinSock2.h>
#include <string>
#pragma warning(disable: 4996)
#include <Ws2tcpip.h>
#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define RESET "\x1B[0m"
int main(int argc, char* argv[] )
{
    
    int iResult = 0;
    short Port = 5000;
    char RecvBuf[1024];
    int BufLen = 1024;

    // инициализируем библиотеки
    WSADATA wsaData;
    WORD DLLVersion = MAKEWORD(2, 2);

    // проверка на ошибку
    iResult = WSAStartup(DLLVersion, &wsaData);
    if (iResult != 0) {
        printf(RED "error" RESET);
        exit(1);
    }

    // создаем сокет 
    SOCKET sListen = socket(AF_INET, SOCK_STREAM, 0);
    // проверка на ошибку
    if (sListen == INVALID_SOCKET) {
        printf(RED "socket failed with error: %ld\n" RESET, WSAGetLastError());
        return 1;
    }
    
    // структура для хранения данных об отправителе
    SOCKADDR_IN SenderAddr;
    int SenderAddrSize = sizeof(SenderAddr);

    // заполняем структуру сокета
    SOCKADDR_IN addr;
    int sizeOfAddr = sizeof(addr);
    addr.sin_addr.s_addr = ADDR_ANY;
    addr.sin_port = htons(Port);
    addr.sin_family = AF_INET;
    
    

    iResult = bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
    // проверка на ошибку 
    if (iResult == SOCKET_ERROR) {
        printf(RED "bind failed with error: %d\n" RESET, WSAGetLastError());
        return 1;
    }

    printf(GRN "Server has been started\n" RESET);

    do {

        ZeroMemory(RecvBuf, BufLen);

        iResult = recvfrom(sListen, RecvBuf, 1024, 0, (SOCKADDR*)&SenderAddr, &SenderAddrSize);
        if (iResult == SOCKET_ERROR) {
            printf(RED "recvfrom failed with error: %d\n" RESET, WSAGetLastError());
        }  

        printf("Received message from %s: %s\n", inet_ntoa(SenderAddr.sin_addr), RecvBuf);
        printf(RecvBuf);
        
    } while (iResult > 0);


    closesocket(sListen);

    system("pause");
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2020-04-15
@andrkkk

So you create a TCP (SOCK_STREAM) socket for which you cannot recvfrom
You need SOCK_DGRAM

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question