问题
i am writing a simple multicast application. i intend to run it on localhost.
i have done the following:
char *maddr;
.
.
.
sendfd = socket(...);
struct sockaddr_in sasend;
sasend.sin_family = AF_INET;
sasend.sin_port = htonl(portno);
inet_ntop(maddr, &(sasend.sin_addr.s_addr));
struct sockaddr_in sarecv;
memcpy(&sarecv, &sasend);
recvfd = socket(...);
const int on = 1;
setsockopt(recvfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); // can you explain why
// this is needed
bind(recvfd, &sarecv);
struct ip_mreq mreq;
memcpy(&mreq.imr_multiaddr, &(sasend.sin_addr));
mreq.imr_interface = htonl(INADDR_ANY);
setsockopt(recvfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
char flag = 1;
setsockopt(sendfd, IPPROTO_IP, IP_MULTICAST_LOOP, &flag, 1);
if (fork() == 0) {
while (recvfrom(recvfd)) {
}
}
else {
while (sendto(sendfd)) {
sleep(3);
}
}
in the actual code i am checking the return values of all system calls. the problem is that recvfrom does not return. the process stays blocked in the call to recvfrom.
i have tried running two instances of the program on different shells. it does not help.
also i tried setting loopback flag to 0, it does not help.
i want to run both the programs from localhost.
the multicast address i am using is 239.255.1.2 which i have seen from the book. i think we can use any class D address as we are making the required setsockopt call.
connecting on port 1025
running linux kernel 2.6.25
also how do i check if multicasting support has been compiled into the kernel.
Update:
i did route add -net 224.0.0.0 netmask 240.0.0.0 dev eth0 on the shell. still the problem exists.
回答1:
ok i disabled the firewall and i could get the program running. got help from here
now more problems:
- how to add rules to the firewall to specifically my code to run
- if i do not disable loopback, then i do not get the messages from another process sending on the same multicast group, and if i enable it then my process receives the messages it transmits. this is because i am running both the programs on localhost. is there a way around.
来源:https://stackoverflow.com/questions/1697534/multicast-ip-address-blocked-in-call-to-recvfrom