C++ udp广播。我需要一个套接字来读取另一个套接字来发送吗?
c++ udp broadcast. Do I need a socket to read and another to send?
我见过很多使用两个套接字的例子。一个发送一个接收。但显然两者都可以做到。我所看到的区别是一个被绑定而另一个没有。示例:http://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html
是的,你可以!
但是请注意,下一次读取或接收可能会读取不同的数据报。 UDP 数据报总是可丢弃的你仍然可以用 MsgPEEK 或类似的东西标记你的 recv()
看到这个话题 and this one可能会更好
如果你偷懒这里是题目中的代码
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;
}
我见过很多使用两个套接字的例子。一个发送一个接收。但显然两者都可以做到。我所看到的区别是一个被绑定而另一个没有。示例:http://www.cs.ubbcluj.ro/~dadi/compnet/labs/lab3/udp-broadcast.html
是的,你可以!
但是请注意,下一次读取或接收可能会读取不同的数据报。 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;
}