尝试读取UDP数据报时,recvfrom返回错误

时间:2014-02-28 02:56:29

标签: c++ windows udp winsock recvfrom

我正在尝试制作一个非常简单的UDP服务器,但我似乎无法掌握如何做到这一点。我查看了Microsoft文档,但即使这样我也遇到了这个问题。似乎recvfrom函数返回一个错误并且调用WSAGetLastError告诉我这是一个无效的参数错误,但对我来说似乎参数是正确的:

int main( int argc, const char* argv[])
{
    char request[MAX_REQUEST_LEN];
    int port;
    SOCKET sock;
    bool quit = false;

    port = 11130;

    WSADATA wsaData;
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR)
    {
        cout << "WSAstartup failed" << endl;
        return -1;
    }

    // Create a socket.
    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        WSACleanup();
        cout << "Error at socket" << endl;
        return -1;
    }

    sockaddr_in server, client;
    int c_len = sizeof(client);

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(port);

    bind( sock, (sockaddr *)&server, sizeof(server) );

    while(!quit)
    {
        memset(request,'\0', MAX_REQUEST_LEN);
        int result = recvfrom(sock, request, MAX_REQUEST_LEN, 0, (struct sockaddr*) &client, &c_len);
        cout << "Received: " << request << endl << "recvfrom return: " << result << endl;
           //process request

    }

    closesocket(sock);
    WSACleanup();

    return 0;
}

任何帮助都将不胜感激。

0 个答案:

没有答案