Friday, 18 May 2018

Checks if specified IP is multicast IP

Checks if specified IP is multicast IP


  • IPv4 multicast addresses are defined by the leading address bits of 1110, originating from the classful network design of the early Internet when this group of addresses was designated as Class D.
  • The Classless Inter-Domain Routing (CIDR) prefix of this group is 224.0.0.0/4. The group includes the addresses from 224.0.0.0 to 239.255.255.255.
  • The macro IN_MULTICAST is used to check the IP as multicast, this macro is impleted as part of Linux kernal.
  • The below file contain this macro.
    • https://github.com/torvalds/linux/blob/master/include/uapi/linux/in.h#L268
  • The userlevel application header file netinet/in.h & arpa/inet.h contain this macro definition.

Program:



#include <stdio.h>
#include <stdbool.h>   // For bool

// For inet_addr
#include <sys/socket.h>
#include <netinet/in.h>    // This contain the in_addr_t, & IN_MULTICAST macro
#include <arpa/inet.h>  // This also including  <netinet/in.h>

/*
  IN_MULTICAST macro is defined in Linux in.h file,
  Below is the definition
  */

//#define IN_CLASSD(a)            ((((long int) (a)) & 0xf0000000) == 0xe0000000)
//#define IN_MULTICAST(a)         IN_CLASSD(a)


bool isMulticastAddress(in_addr_t s_addr)
{
    //in_addr_t stored in network order
    uint32_t address = ntohl(s_addr);
    char *char_saddr = (char*) &s_addr;
    char *char_address = (char *) &address;

    printf("S-add value = %x %x %x %x address = %x %x %x %x \n", char_saddr[0], char_saddr[1], char_saddr[2], char_saddr[3],
                    char_address[0], char_address[1], char_address[2], char_address[3]);

    return (address & 0xF0000000) == 0xE0000000;
}

int main()
{
    int ret = 0;

    if (IN_MULTICAST(ntohl(inet_addr("239.4.4.4")))) {
        printf("239.4.4.4 is an multicast using IN_MULTICAST macro. \n");
    }
    else {
        printf("Not an multicast IP check using IN_MULTICAST macro. \n");
    }


    ret = isMulticastAddress(inet_addr("239.4.4.4"));
    if(ret) {
        printf("239.4.4.4 is an multicast using isMulticastAddress function. \n");
    }
    else {
        printf("Not an multicast IP check using isMulticastAddress function. \n");
    }

    ret = isMulticastAddress(inet_addr("224.4.4.4"));
    if(ret) {
        printf("224.4.4.4 is an multicast using isMulticastAddress function. \n");
    }
    else {
        printf("Not an multicast IP check using isMulticastAddress function. \n");
    }


}

Output:

sample$ ./a.out
239.4.4.4 is an multicast using IN_MULTICAST macro.
S-add value = ffffffef 4 4 4 address = 4 4 4 ffffffef
239.4.4.4 is an multicast using isMulticastAddress function.
S-add value = ffffffe0 4 4 4 address = 4 4 4 ffffffe0
224.4.4.4 is an multicast using isMulticastAddress function.


Refer: http://www.tcpipguide.com/free/t_IPMulticastAddressing.htm

No comments:

Post a Comment