Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Multicast on a specific NIC

    Hi all,

    I am trying to setup a socket that listens and send on a specific NIC. This socket also joins a multicast group. For some reason it doesn't work. Here is a sample code of what I do:

    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>

    #define MY_IP ""
    #define MY_PORT 52101
    #define MY_MC ""

    int main()
    int sock = socket (AF_INET, SOCK_DGRAM, 0);
    if (sock <= 0)
    return -1;

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr (MY_IP);
    addr.sin_port = htons (MY_PORT);

    int ret = bind (sock, (sockaddr*)&addr, sizeof (addr));
    if (ret != 0)
    return -1;

    ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = inet_addr (MY_MC);
    mreq.imr_interface.s_addr = inet_addr (MY_IP);

    ret = setsockopt (sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq));
    if (ret != 0)
    return -1;

    char buff[1500];
    ret = recv (sock, buff, sizeof (buff), 0);
    if (ret <= 0)
    printf ("Error in recv!\n");
    return -1;

    printf ("Received packet from MC!!");
    return 0;

    In this sample the recv function never returns. If I change MY_IP to be INADDR_ANY the function recv returns. In my application I want to get only packets from a specific interface and not from all of them.

    Thx in advance for help.

  2. #2
    instead of:

    mreq.imr_interface.s_addr = inet_addr (MY_IP);

    i think you want:


    if that's not the issue then i can look more closely...

  3. #3

    Thank you for answering.
    What I meant was that if I replace the line:

    addr.sin_addr.s_addr = inet_addr (MY_IP);


    addr.sin_addr.s_addr = htonl (INADDR_ANY);

    then it works fine and my socket receives multicast packets. The problem is that in this case I also receive non-multicast packets with destination port=MY_PORT which arrived on other interfaces.

  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts