While working on a custom packet injector for Linux, I had to calculate the network and broadcast IP addresses given an IP address and a netmask. After searching on Google I found that the calculations are some very simple bitwise operations.
To get the network address perform a bitwise AND on the IP address and the netmask:
network = ip & netmask
To get the broadcast address perform a bitwise OR on the network address and the complement of the netmask:
broadcast = network | ~netmask
Here a simple C program you can use to calculate the network and broadcast addresses on your own:
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
struct in_addr ip;
struct in_addr netmask;
struct in_addr network;
struct in_addr broadcast;
if (argc != 3)
{
printf("usage: %s ip netmask\n", argv[0]);
exit(0);
}
inet_aton(argv[1], &ip);
inet_aton(argv[2], &netmask);
// bitwise AND of ip and netmask gives the network
network.s_addr = ip.s_addr & netmask.s_addr;
printf("network %s\n", inet_ntoa(network));
// bitwise OR of network and complement of netmask gives the broadcast
broadcast.s_addr = network.s_addr | ~netmask.s_addr;
printf("broadcast %s\n", inet_ntoa(broadcast));
return 0;
}
To compile it use the command:
gcc -Wall ipcalc.c -o ipcalc
The usage is really simple:
$ ./ipcalc usage: ./ipcalc ip netmask $ ./ipcalc 192.168.1.0 255.255.255.0 network 192.168.1.0 broadcast 192.168.1.255
Feel free to use it and send me comments/suggestions