Search code examples
c++socketsudpbroadcast

c++ udp broadcast. Do I need a socket to read and another to send?


I have seen many examples where they use two sockets. One to send and one to receive. But apparently both can do it. The difference that I have seen is that one is binded and another not. Example: http://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html


Solution

  • Yes you can !

    However Just be cautioned that the next read or recv might read a different datagram. UDP datagrams are always discardable you can still flag your recv() with MsgPEEK or something like that

    see this topic here and this one may be better

    if your lazy here is the code from the topic

     struct sockaddr_in si_me, si_other;
        int s, i, blen, slen = sizeof(si_other);
        char buf[BUFLEN];
    
        s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (s == -1)
            die("socket");
    
        memset((char *) &si_me, 0, sizeof(si_me));
        si_me.sin_family = AF_INET;
        si_me.sin_port = htons(1234);
        si_me.sin_addr.s_addr = htonl(192.168.1.1);
    
        if (bind(s, (struct sockaddr*) &si_me, sizeof(si_me))==-1)
            die("bind");
    
        int blen = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*) &si_other, &slen);
        if (blen == -1)
           diep("recvfrom()");
    
        printf("Data: %.*s \nReceived from %s:%d\n\n", blen, buf, inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
    
        //send answer back to the client
        if (sendto(s, buf, blen, 0, (struct sockaddr*) &si_other, slen) == -1)
            diep("sendto()");
    
        close(s);
        return 0;
    }