Reputation: 3390
If user enters some IP address like "239.4.4.4", how can I determine this IP address is multicast using any function if available in linux C?
Upvotes: 3
Views: 14386
Reputation: 1409
With Linux, you can use the IN_MULTICAST()
macro defined in in.h
. For example,
bool a = IN_MULTICAST(ntohl(inet_addr("239.4.4.4")));
Upvotes: 4
Reputation: 51
bool isMulticastAddress(in_addr_t s_addr)
{
//in_addr_t stored in network order
uint32_t address = ntohl(s_addr);
return (address & 0xF0000000) == 0xE0000000;
}
Upvotes: 5
Reputation: 33076
IPv4 multicast addresses are defined by the most significant bits 1110
, so:
if the IP address is stored as 32bit unsigned variable, apply a >> 28
to the variable, then check if the result is 14
(1110
), like isMulti = ((address >> 28) == 14);
.
if the IP address is stored as a tuple of 4 unsigned chars, then check if the first (MSB) is between 224 and 239, included.
Upvotes: 7
Reputation: 3390
/**********************************************************************************************************************
* Checks if specified IP is multicast IP. Multicast IP ranges from 224.0.0.0 to 239.255.255.255.
*
* Returns 0 if specified IP is not multicast IP, else non-zero.
*
* Parameters:
* ip IP to check for multicast IP, stored in network byte-order.
*********************************************************************************************************************/
int net_ip__is_multicast_ip(in_addr_t ip){
char *ip_str = (char *) &ip;
int i = ip_str[0] & 0xFF;
// we will check only first byte of IP
// and if it from 224 to 239, then it can
// represent multicast IP.
if(i >= 224 && i <= 239){
return 1;
}
return 0;
}
Upvotes: 0
Reputation: 24802
you don't need a function to determine whether an address is a multicast one, just look at its range: if the first byte is between 224 and 239 (included), it's a multicast address, within the class D.
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
Of course IPv6 has its own scheme, but there multicast addresses start with ff00::
. Anyway, refer to the wikipedia article for that.
Oh, and finally, if you want us to give you ways of checking that in C, you need to give more details on what is the representation of your IP address. Is it a 4 bytes struct? Is it a four bytes integer? Is it an array of characters?
Upvotes: 2
Reputation: 1196
Multicast addresses ranges from 224.0.0.0 to 239.255.255.255.http://en.wikipedia.org/wiki/Multicast_address
So it should be enough for you to check the whether the address falls within range.
Upvotes: 3