Listening to a UDP broadcast

☆樱花仙子☆ 提交于 2019-12-23 03:00:14

问题


I need to listen to a network broadcast coming over UDP. The datagram contains a j4cDAC_broadcast struct. I have tried following a few tutorials, but they seem to have left a few things out and dont have very detailed explanations, if any.

With what I have right now I am getting an error BIND FAILED 10049 and error 10049 indicates that the address is unavailable. The broadcast is coming in on 255.255.255.255:7654. How do I fix this error?

This is what I have so far:

void test() 
    {
    WSADATA  wsd;
    SOCKET s;
    j4cDAC_broadcast recieve;
    char *read = (char*) malloc(sizeof(j4cDAC_broadcast));
    int ret;
    DWORD dwSenderSize;
    sockaddr_in local;

    if (WSAStartup(MAKEWORD(2,2),&wsd) != 0)
        {
        cout << "WSAStartup failed";
        exit(1);
        }

    local.sin_family = AF_INET;
    local.sin_port = htons ((short)BCASTPORT);
    local.sin_addr.s_addr = inet_addr(BCASTIP);


    s = socket(AF_INET, SOCK_DGRAM, 0 );

    if (s == INVALID_SOCKET)
        {
        cout << "SOCKET FAILED!: " << WSAGetLastError();               
        exit(1);
        }

    int bnd = bind(s,(SOCKADDR*) &local,sizeof(local) );

    if (bnd != 0 )
        {
        cout << "BIND FAILED: " << WSAGetLastError();     //fails here
        return;
        }


    ret = recv (s, read,sizeof(j4cDAC_broadcast),0);

    if (ret == SOCKET_ERROR)
        {
        cout << "RECIEVE FAILED " << WSAGetLastError();            
        return;
        }

    memcpy(&recieve,read,sizeof(read));


    closesocket(s);

    WSACleanup();
    }

Also, another thing I couldn't find was how to get the IP address of the sender out of the header.


回答1:


You don't bind to the broacast address; you bind to the machine's local IP (or 0.0.0.0 for all of them). The broadcasts will reach the socket all the same. That's why it's a broadcast. The logic of "this packet is sent to a broadcast address, means we wanna receive it" happens on the TCP/IP stack level.

Don't bind to 127.0.0.1.

To get the sender's address, use recvfrom() and note the penultimate parameter.



来源:https://stackoverflow.com/questions/8017803/listening-to-a-udp-broadcast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!