首页 > 解决方案 > c++ udp 广播。我需要一个套接字来读取和另一个来发送吗?

问题描述

我见过很多他们使用两个套接字的例子。一个发送一个接收。但显然两者都可以做到。我看到的区别是一个是绑定的,另一个不是。示例:http ://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html

标签: c++socketsudpbroadcast

解决方案


是的你可以 !

但是请注意,下一次 read 或 recv 可能会读取不同的数据报。UDP 数据报总是可以丢弃的,你仍然可以用 MsgPEEK 或类似的东西标记你的 recv()

在这里看到这个主题,这个主题可能会更好

如果您的懒惰是该主题的代码

 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;
}

推荐阅读