perl and network addresses
Ben Scott
dragonhawk at gmail.com
Mon Mar 27 16:06:01 EST 2006
On 3/27/06, Paul Lussier <p.lussier at comcast.net> wrote:
> I'm stumped. I've got a network address space of 10.0.32/19. How
> ever, this space is carved up using a /16 netmask.
HUH?
> Given an address, say 10.0.33.189, I want to get the "network" and
> "host" portion of the address.
(1) Red Hat provides a nifty utility called "ipcalc" that will do
that for you. E.g.:
$ ipcalc -b -m -n -p 10.0.33.189/19
NETMASK=255.255.224.0
PREFIX=19
BROADCAST=10.0.63.255
NETWORK=10.0.32.0
$
(2) I find it's a lot easier to conceptualize this stuff if you
write it out in binary notation (view using a fixed-width font):
/19 = 255.255.224.0
010.000.033.189 = 00001010 00000000 00100001 10111101
255.255.224.000 = 11111111 11111111 11100000 00000000
Net portion = 00001010 00000000 00100000 00000000
Node portion = 00000000 00000000 00000001 10111101
(3) You mentioned Perl, but this is the same in most programming
languages: It's simple binary arithmetic and Boolean logic. All you
need are AND and NOT (complement). The trickier part is usually
converting from dotted-quad notation to binary storage. Fortunately,
Unix provides a function for that: inet_addr(2). C code looks like
this:
/* includes */
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
/* main program */
int main() {
/* variables */
unsigned int a; /* address */
unsigned int m; /* mask */
unsigned int n; /* node */
/* get address and mask, in network byte order */
a = inet_addr("192.0.2.42");
m = inet_addr("255.255.255.0");
/* find node portion by AND'ing with complement of net-mask */
n = a & (~m);
/* convert to host byte order */
n = ntohl(n);
/* print result as decimal integer */
printf("node=%d\n", n);
}
I tried
perl -we '$a = inet_addr("192.0.2.42");'
but it complained that inet_addr is not defined. I suspect there's a
module somewhere you need to pull in. Hopefully this is enough to get
you started.
-- Ben
More information about the gnhlug-discuss
mailing list