5 * Copyright (C) 2007-2010 Intel Corporation. All rights reserved.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2 as
9 * published by the Free Software Foundation.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27 #include <arpa/inet.h>
29 static unsigned char netmask2prefixlen(const char *netmask)
31 unsigned char bits = 0;
32 in_addr_t mask = inet_network(netmask);
33 in_addr_t host = ~mask;
35 /* a valid netmask must be 2^n - 1 */
36 if ((host & (host + 1)) != 0)
39 for (; mask; mask <<= 1)
45 int main(int argc, char *argv[])
47 const char *masks[] = { "255.255.255.255", "255.255.255.0",
48 "255.255.0.0", "255.0.0.0" };
52 for (i = 0; i < 4; i++) {
53 printf("subnet %-16s prefixlen %u\n", masks[i],
54 netmask2prefixlen(masks[i]));
59 for (i = 0; i < 4; i++) {
61 addr.s_addr = htonl(~(0xfffffffflu >> len));
62 printf("prefixlen %-2u netmask %s\n", len, inet_ntoa(addr));