Skip to content

Instantly share code, notes, and snippets.

@tetheredge
Forked from MrPeanutButta/ipv4_broadcast_addr.c
Created November 8, 2013 16:15
Show Gist options
  • Save tetheredge/7373460 to your computer and use it in GitHub Desktop.
Save tetheredge/7373460 to your computer and use it in GitHub Desktop.
#include <cstdint>
#include <arpa/inet.h>
/** Returns the IPv4 broadcast address for a given subnet.
*
* Assuming host is little endian.
* Assuming your host is Linux :)
*
* subtracting 1 from the return will yield last usable host address.
*
* @param prefix : network subnet (network byte order).
* @param length : CIDR bit length.
* @return : highest possible IPv4 address (network byte order).
*/
uint32_t ipv4_broadcast_addr(const uint32_t &prefix, const uint8_t &length) {
/* A bit length > 32 is invalid.
* Returning 0 is not safe and may represent
* a default route in nearly all cases */
if(length > 32) return 0;
// fill netmask with 255.255.255.255 and shift left the remaining bits
uint32_t netmask = 0xFFFFFFFF << (32 - length);
// temp value, convert network byte order to host byte order
uint32_t tmp_prefix = ntohl(prefix);
// add bits from inverse netmask to the subnet
tmp_prefix |= (~netmask);
// return network byte order of our IP
return htonl(tmp_prefix);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment