数据包丢失存在问题。我正在进行套接字连接以获取udp数据包,但我认为我的多播套接字连接可能存在问题。请帮帮我 - 我的代码是否合适?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main(int argc, char *argv[])
{
struct sockaddr_in si_me, si_other;
struct ip_mreq mreq;
socklen_t slen = sizeof(si_other);
int s = -1;
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
printf("Error creating socket\n");
}
int yes = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
printf("setsockopt");exit(1);
}
int val = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, (const char *) &val,
sizeof(val)) < 0) {
}
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(42000);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
//bind socket to port
if (bind(s, (struct sockaddr*) &si_me, sizeof(si_me)) == -1) {
printf("Error binding to port\n");
}
//multicast socket
mreq.imr_multiaddr.s_addr = inet_addr("232.0.1.1");
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
printf("setsockopt mreq");
exit(1);
}
int recv_len;
while(true) {
if ((recv_len = (int) recvfrom(s, data, BUFLEN, 0,(struct sockaddr *) &si_other, &slen)) == -1) {
printf("Error receiving pakcets\n");
}
}
}