Broadcast address from CIDR – PHP/MySQL

When working with subnets in CIDR (Classless Inter-Domain Routing) notation, for example, you may find yourself needing to know the broadcast address. Normally I would use ipcalc, which can be found in net-mgmt/ipcalc within the FreeBSD ports tree. However it is not always conviniant to use a 3rd party program, escpecially when needing to do the conversion inside some code.

So the awnser, a simple equation to get the broadcast address from the network address and cidr.


The broadcast address is the network IP, plus, 32 minus the CIDR, to the power of 2, minus 1.

An example of this, find the broadcast address from + (2^(32-26)) - 1 =

So, the broadcast address is There is one problem with this example. How is it I can use an IP address as if it were an integer? Before this equation can be executed we must first convert the IP address into an integer. There are many ways to achieve this, in MySQL you would use the INET_ATON() function, in PHP you would use ip2long(). Lets look at the previous example again, but this time lets use an integer representation of the IP address.

Find the broadcast address from, where the IP address is first converted to an integer

3232243776 + (2^(32-26)) - 1 = 3232243839

N.B. this conversion was done using a 64 bit CPU. On a 64bit CPU, = 323224377 and on a 32bit CPU, = -1062723457. This make no differance to the equation, it will work on both 32 and 64 bit architectures.

Converting these integers back to an IP address is simple, for MySQL we use INET_NTOA() and for PHP we use long2ip().

Lets check our work

long2ip(3232243776) =  // Network
long2ip(3232243839) = // Broadcast

Here is an example SQL query to get the broadcast from CIDR

mysql> SELECT INET_NTOA(INET_ATON('') + (pow(2, (32-26))-1));
| INET_NTOA(INET_ATON('') + (pow(2, (32-26))-1)) |
|                                              |
1 row in set (0.00 sec)

Here is an example PHP function to get the broadcast from CIDR

function cidr2broadcast($network, $cidr)
    $broadcast = long2ip(ip2long($network) + pow(2, (32 - $cidr)) - 1);

  return $broadcast;

$network = "";
$cidr    = 20;

print(cidr2broadcast($network, $cidr));

You may also like...