使用winsock时为什么不接收UDP数据包?

时间:2013-11-28 16:51:17

标签: c++ sockets udp winsock

我正在尝试编写两个程序,一个发送udp数据包,另一个接收它们。我的问题是接收程序没有打印数据包,即使wireshark显示它们被发送到正确的位置。

这是我的代码:
UDP_Send.cpp

    #include <WinSock2.h>
    #include <WS2tcpip.h>
    #include <iostream>
    #include <string>

    using namespace std;

    #define PORT_NUM "17140"

    int main()
    {
    int sock;
    addrinfo* sockInfo;
    addrinfo hints;

    //Initialize winsock
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 0), &wsaData))
        cout << "Error initializing winsock\n";

    //get the address info for the receiving end of this
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    if (getaddrinfo("192.168.1.9", PORT_NUM, &hints, &sockInfo) != 0)
    {
        cout << "Error getting the address info\n";
    }

    //Get the socket
    sock = socket(sockInfo->ai_family, sockInfo->ai_socktype, sockInfo->ai_protocol);
    if(sock == -1)
        cout<<"Error creating the socket\n";

    //Send the message to the receiver
    while (true)
    {
        string msg = "hello world";
        int i = sendto(sock, msg.c_str(), msg.length(), 0, sockInfo->ai_addr, sockInfo->ai_addrlen);
        if (i == -1)
            cout << "Error sending the packet\n";
    }

    //Clean up winsock
    WSACleanup();

    return 1;
    }

UDP_Receive.cpp

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iostream>

using namespace std;

#define PORT_NUM "17140"

int main()
{
    int sock;
    addrinfo* sockInfo;
    addrinfo hints;

    //Initialize winsock
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 0), &wsaData))
        cout << "Error initalizing winsock\n";

    //Get the address info of this program
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_protocol = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE;

    int check = getaddrinfo(NULL, PORT_NUM, &hints, &sockInfo);
    if (check != 0)
        cout << WSAGetLastError();

    //Get the socket
    sock = socket(sockInfo->ai_family, sockInfo->ai_socktype, sockInfo->ai_protocol);
    if (sock == -1)
        cout << "Error creating the socket\n";

    //Bind to the socket
    if (bind(sock, sockInfo->ai_addr, sockInfo->ai_addrlen) == -1)
        cout << "Error creating the socket\n";

    //Recieve data from the socket
    while (true)
    {
        char msg[20];
        memset(&msg, 0, sizeof(msg));
        check = recvfrom(sock, msg, sizeof(msg), 0, NULL, NULL);
        cout << msg << endl;
    }

    WSACleanup();

    return 1;
}

谢谢。

1 个答案:

答案 0 :(得分:1)

我发现了问题,这只是一个简单的错误。

//Get the address info of this program
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_protocol = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;

应该是

//Get the address info of this program
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_DGRAM; //this is where the change is
hints.ai_flags = AI_PASSIVE;

现在可行。