c++ - c++ udp 广播。我需要一个套接字来读取和另一个来发送吗?
问题描述
我见过很多他们使用两个套接字的例子。一个发送一个接收。但显然两者都可以做到。我看到的区别是一个是绑定的,另一个不是。示例:http ://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html
解决方案
是的你可以 !
但是请注意,下一次 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;
}
推荐阅读
- php - Codeigniter - 在 mysql 中保存输入值
- c# - 如何从相关实体获得最大或最小结果?
- angular - 当我尝试从 b64 下载文件时,导航器出现红色错误
- sql - 根据日期执行存储过程
- python - 在用户模式下在 linux 上安装 tkinter for python
- sql - 如何使用 SQL 中的附加组合值从一个表插入另一个表?
- python - pyqt5 无法在 qlistwidget 级别连接项目小部件信号
- javascript - 如何在香草JS中从位置过渡到动画?
- macos - 您将如何在最新的 macOS 上通过 nix 安装 openconnect?
- jmeter - 如何使用来自 HTTP Header Manager 的 Jmeter 捕获 X-CSRF-TOKEN