简体   繁体   English

Winsock:UDP recvfrom() 未填写用于发送数据的相同 IP 地址

[英]Winsock: UDP recvfrom() not filling in the same IP address that was used to send data

I am coding a UDP echo client & server.我正在编写 UDP echo 客户端和服务器。 These are both running on my machine.这些都在我的机器上运行。 The client is set up to send the message to the IP address::1.客户端设置为将消息发送到 IP 地址::1。 At this point my server receives the message and is supposed to print something similar to this.此时,我的服务器收到消息并应该打印类似的内容。

Processing client at::1

Instead the server keeps getting a different IP address.相反,服务器不断获得不同的 IP 地址。

Processing client at 132:e3d5::

Note: The IP address received is different every time.注意:每次收到的IP地址都不一样。

This is causing a problem because I believe when I later try to echo the message back to my client, I can't send it to the correct place because the IP address I received is not the same as::1.这导致了一个问题,因为我相信当我稍后尝试将消息回显给我的客户端时,我无法将其发送到正确的位置,因为我收到的 IP 地址与::1 不同。

Here is some code:这是一些代码:

Client.c客户端.c

void main(int argc, char* argv[])   // argc is # of strings following command, argv[] is array of ptrs to the strings
{
    WSADATA wsaData;                // contains details about WinSock DLL implementation
    struct sockaddr_in6 serverInfo; // standard IPv6 structure that holds server socket info
    char* serverIPaddr, * phrase, echoBuffer[RCVBUFSIZ];
    int serverPort, msgLen, fromSize, echoLen;

    // Verify correct number of command line arguments
    if (argc != 4) {
        printf("Invalid amount of arguments entered. \nPlease make sure to only enter the following: \n\n <application name> <ip address> <port number> <message>");
        exit(1);
    }

    // Retrieve the command line arguments.
    // to be converted from char to int. 
    serverIPaddr = argv[1];
    serverPort = atoi(argv[2]);
    phrase = argv[3];
    msgLen = strlen(phrase) + 1; // We are sending the null terminator

    // Initialize Winsock 2.0 DLL. 
    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
        // Failed
        printf("Couldn't initialize Winsock 2.0 DLL");
        exit(1);
    }

    // Create an IPv6 UPD stream socket.  Now that Winsock DLL is loaded, we can signal any errors as shown on next line:
    int sock;
    sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        DisplayFatalErr("socket() function failed.");
        exit(1);
    }
    printf("Socket created successfully. Press enter to continue...");
    getchar();

    memset(&serverInfo, 0, sizeof(serverInfo));
    serverInfo.sin6_family = AF_INET6;
    serverInfo.sin6_port = htons(serverPort);
    inet_pton(AF_INET6, serverIPaddr, &serverInfo.sin6_addr);

    if (msgLen == 0) {
        DisplayFatalErr("Message was empty, please make sure to include a message.");
        exit(1);
    }

    // Send data to server
    if (sendto(sock, phrase, msgLen, 0, (struct sockaddr*) & serverInfo, sizeof(serverInfo)) != msgLen) {
        DisplayFatalErr("sendto() function failed.");
        exit(1);
    }

    fromSize = sizeof(serverInfo);
    if ((echoLen = recvfrom(sock, echoBuffer, RCVBUFSIZ, 0, (struct sockaddr*) & serverInfo.sin6_addr, &fromSize)) != msgLen) {
        // We lost some data check for error first
        if (echoLen < 0) {
            DisplayFatalErr("recvfrom() function failed.");
            exit(1);
        }
    }

    // Output message (Will create soon)

    printf("");
    printf("\nData was received from the server. Press enter to continue...");
    getchar();

    if (closesocket(sock) != 0) {
        DisplayFatalErr("closesocket() function failed.");
    }
    printf("socket closed successfully. Press enter to continue...");
    getchar();

    if (WSACleanup() != 0) {
        DisplayFatalErr("WSACleanup() function failed.");
    }

    exit(0);
}

Server.c服务器.c

void main(int argc, char* argv[])   // argc is # of strings following command, argv[] is array of ptrs to the strings
{
    WSADATA wsaData;                // contains details about WinSock DLL implementation
    struct sockaddr_in6 serverInfo; // standard IPv6 structure that holds server socket info
    int serverPort, clientSock, rcvLen, fromSize;
    char* rcvBuffer[RCVBUFSIZ];
    serverPort = 0;

    // Verify correct number of command line arguments
    if (argc != 2) {
        serverPort = DEFAULT_PORT;
    }
    else {
        serverPort = atoi(argv[1]);
    }

    // Initialize Winsock 2.0 DLL
    if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
        // Failed
        printf("Couldn't initialize Winsock 2.0 DLL");
        exit(1);
    }

    // Create an IPv6 UDP stream socket.
    int sock;
    sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
    if (sock == INVALID_SOCKET) {
        DisplayFatalErr("socket() function failed.");
        exit(1);
    }

    // Don't forget any necessary format conversions.
    memset(&serverInfo, 0, sizeof(serverInfo));
    serverInfo.sin6_family = AF_INET6;
    serverInfo.sin6_port = htons(serverPort);
    serverInfo.sin6_addr = in6addr_any;
    //inet_pton(AF_INET6, serverIPaddr, &serverInfo.sin6_addr);

    // Bind the server socket to the sockadder structure.
    if (bind(sock, (struct sockadder*) & serverInfo, sizeof(serverInfo)) == SOCKET_ERROR) {
        DisplayFatalErr("bind() function failed.");
        exit(1);
    }

    printf("ST's IPv6 echo server is ready for client connection on port: %i\r\n", serverPort);


    // Forever Loop waiting for messages
    for (;;) {
        struct sockaddr_in6 clientInfo; // Hold client port & adder recvfrom
        memset(&clientInfo, 0, sizeof(clientInfo));
        clientInfo.sin6_family = AF_INET6;

        fromSize = sizeof(clientInfo);
        if ((rcvLen = recvfrom(sock, rcvBuffer, RCVBUFSIZ, 0, (struct sockaddr*) & clientInfo.sin6_addr, &fromSize)) < 0) { //THIS IS WHERE I BELIEVE THE ERROR TO BE. WHEN LOOKING AT THE ADDRESS ON THE DEBUGGER IT DOESN'T MATCH THE ONE I SENT USING THE CLIENT
            DisplayFatalErr("recvfrom() function failed.");
        }

        // Processing Socket
        char* clientAddr[INET6_ADDRSTRLEN];
        inet_ntop(AF_INET6, &(clientInfo.sin6_addr), clientAddr, INET6_ADDRSTRLEN);
        int clientPort = ntohs(clientInfo.sin6_port);

        printf("Processing the client at %s, client port %i, server port %i.\r\n", clientAddr, clientPort, serverPort);
        printf("Message Received: %s\r\n", rcvBuffer);
        // Send data back
        if (sendto(sock, rcvBuffer, rcvLen, 0, (struct sockaddr*) & clientInfo, sizeof(clientInfo)) != rcvLen) {
            DisplayFatalErr("sendto() function failed.");
        }
    }
}

Let me know if you need me to provide any other information.如果您需要我提供任何其他信息,请告诉我。

You are correct, the problem is here:你是对的,问题出在这里:

if ((rcvLen = recvfrom(sock, rcvBuffer, RCVBUFSIZ, 0, (struct sockaddr*) & clientInfo.sin6_addr, &fromSize)) < 0) {
//                                                                                   ^^^^^^^^^^

You are not passing a sockaddr * , you are passing a struct in6_addr * .您没有传递sockaddr * ,而是传递了struct in6_addr * Just drop the .sin6_addr part:只需删除.sin6_addr部分:

if ((rcvLen = recvfrom(sock, rcvBuffer, RCVBUFSIZ, 0, (struct sockaddr*) & clientInfo, &fromSize)) < 0) {

When the server calls recvfrom() , you are passing it an in6_addr* instead of a sockaddr_in6* in the from parameter.当服务器调用recvfrom()时,您将在from参数中传递一个in6_addr*而不是sockaddr_in6* You need to pass in a pointer to the whole sockaddr_in6 , not a pointer to just its sin6_addr field:您需要传入一个指向整个sockaddr_in6的指针,而不是指向其sin6_addr字段的指针:

recvfrom(..., (struct sockaddr*) &clientInfo, ...) // <-- NOT &clientInfo.sin6_addr!

There are other problems in the server, too.服务器中还有其他问题。

Once the server has received a message, it is calling inet_ntop() to convert the client's source IP address to a string.一旦服务器收到消息,它就会调用inet_ntop()将客户端的源 IP 地址转换为字符串。 However, it passing in a char*[] array, but it needs to pass in a char[] array instead:但是,它传入了一个char*[]数组,但它需要传入一个char[]数组:

char clientAddr[INET6_ADDRSTRLEN]; // <-- char, NOT char*!
inet_ntop(AF_INET6, &(clientInfo.sin6_addr), clientAddr, INET6_ADDRSTRLEN);

Also, when printing out the received message, you are treating it as a null-terminated string.此外,在打印出接收到的消息时,您会将其视为以空字符结尾的字符串。 Which is fine in this example since your client is sending a null terminator, but that is not a good idea for your server to rely on in general.在此示例中这很好,因为您的客户端正在发送 null 终结器,但这对于您的服务器来说通常不是一个好主意。 That is a good way for malicious clients to cause buffer overflow attacks.这是恶意客户端引发缓冲区溢出攻击的好方法。 You should instead use the actual byte size that recvfrom() returns:您应该改用recvfrom()返回的实际字节大小:

printf("Message Received: %.*s\r\n", rcvLen, rcvBuffer);

And when calling sendto() to echo the message back to the client, you should use the actual fromSize reported by recvfrom() instead of using sizeof(clientInfo) for the client's address size:当调用sendto()将消息回显给客户端时,您应该使用recvfrom()报告的实际fromSize而不是使用sizeof(clientInfo)作为客户端的地址大小:

sendto(..., (struct sockaddr*) &clientInfo, fromSize)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM