在VS2013中使用UDP套接字接收数据

时间:2014-09-09 09:09:04

标签: c sockets udp bind

我希望按端口*.xml收到3702个数据。

所以我做了一个示例Server。并通过三个端口1500,2500,3702发送数据。(在第43行编辑PORT)

它从端口1500,2500正确工作并打印数据。 但是当我将PORT设置为3702时。

它给我一个错误:**Bind failed with error code :10048**

我发现其他客户端IP可能存在于我的局域网中的PORT 3702发送数据。 我该如何解决?

#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

#define BUFLEN 8192  //Max length of buffer
#define PORT 3702   //The port on which to listen for incoming data

int main()
{
    SOCKET s;
    struct sockaddr_in server, si_other;
    int slen, recv_len;
    char buf[BUFLEN];
    WSADATA wsa;

    slen = sizeof(si_other);

    //Initialise winsock
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Initialised.\n");

    //Create a socket
    if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d", WSAGetLastError());
    }
    printf("Socket created.\n");

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(PORT);

    //Bind
    if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    puts("Bind done");

    //keep listening for data
    while (1)
    {
        printf("Waiting for data...");
        fflush(stdout);

        //clear the buffer by filling null, it might have previously received data
        memset(buf, '\0', BUFLEN);

        //try to receive some data, this is a blocking call
        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) ==     SOCKET_ERROR)
        {
            printf("recvfrom() failed with error code : %d", WSAGetLastError());
            //exit(EXIT_FAILURE);
        }

        //print details of the client/peer and the data received
        printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
        printf("Data: %s\n", buf);

        //now reply the client with the same data

    }

    closesocket(s);
    WSACleanup();
    return 0;
}

1 个答案:

答案 0 :(得分:1)

这是由于地址已在使用

通常,每个套接字地址(协议/ IP地址/端口)只允许使用一次。如果应用程序尝试bind套接字已经用于现有套接字的IP地址/端口,或者未正确关闭的套接字,或者仍在关闭的套接字,则会发生此错误。对于需要bind多个套接字到同一端口号的服务器应用程序,请考虑使用setsockoptSO_REUSEADDR)。

客户端应用程序通常不需要调用bind - connect自动选择未使用的端口。当使用通配符地址(涉及ADDR_ANY)调用bind时,可能会延迟WSAEADDRINUSE错误,直到提交特定地址为止。稍后调用其他函数可能会发生这种情况,包括connectlistenWSAConnectWSAJoinLeaf