1

There is a problem with packets drops. I am doing socket connection to get udp packets, but I think there may be a problem in my multi-cast socket connection. Please help me — is my code proper or not?

#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");
         }
    }
}
dbush
  • 205,898
  • 23
  • 218
  • 273
manish thanki
  • 120
  • 1
  • 8
  • Please tell us what you see when packets are lost. In my answer below I assumed it's `Error receiving pakcets`. – meaning-matters Jul 14 '15 at 07:34
  • 1
    If you get an error from a system call you must call `perror()` or use `errno` or `strerror()` in an error message, immediately, without calling any other system calls in between. Without that, your question is just a guessing game. Please fix your code and advise the result. – user207421 Jul 14 '15 at 08:08

0 Answers0