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
Recently I had to create a vmware image with Debian GNU/Linux that had to be as small as possible because people would have to download it. I started installing Debian “sid” by using debootstrap according to the following instructions:
Curiosity and laziness are the two most important reasons that my system ends up with lots of useless software after a couple months of usage. Many times I want to test drive a program and if it suits my needs I’ll keep it otherwise it will end up in /dev/null.
Whenever I format my computer (and trust me that happens really often) I want only the programs I use to be installed and nothing else. I don’t like having my machine overloaded with crappy software that I never use (that’s the case with Microsoft Windows). So every time I have to remember which programs I want and install them one by one with apt-get. For that reason I decided to create a list with all the programs I need. In that way I can just copy – paste the list every time I format.