Last active
December 17, 2015 03:09
-
-
Save MrPeanutButta/5541411 to your computer and use it in GitHub Desktop.
Returns the highest IP address in subnet range.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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