1 /* vi: set sw=4 ts=4 ai: */
3 * Mini ipcalc implementation for busybox
5 * By Jordan Crouse <jordan@cosmicpenguin.net>
6 * Stephan Linz <linz@li-pro.net>
8 * This is a complete reimplentation of the ipcalc program
9 * from Redhat. I didn't look at their source code, but there
10 * is no denying that this is a loving reimplementation
17 #include <sys/socket.h>
18 #include <netinet/in.h>
19 #include <arpa/inet.h>
23 #define IPCALC_MSG(CMD,ALTCMD) if (mode & SILENT) {ALTCMD;} else {CMD;}
25 static unsigned long get_netmask(unsigned long ipaddr)
28 return 0x00FFFFFF; /* Class C */
31 return 0x0000FFFF; /* Class B */
33 return 0x000000FF; /* Class A */
37 #define BROADCAST 0x02
42 int ipcalc_main(int argc, char **argv)
44 unsigned char mode = 0;
46 unsigned long netmask = 0;
47 unsigned long broadcast = 0;
48 unsigned long network = 0;
49 unsigned long ipaddr = 0;
53 struct option long_options[] = {
54 {"netmask", no_argument, NULL, 'n'},
55 {"broadcast", no_argument, NULL, 'b'},
56 {"network", no_argument, NULL, 'w'},
57 #ifdef CONFIG_FEATURE_IPCALC_FANCY
58 {"hostname", no_argument, NULL, 'h'},
59 {"silent", no_argument, NULL, 's'},
65 while ((opt = getopt_long(argc, argv,
66 #ifdef CONFIG_FEATURE_IPCALC_FANCY
71 long_options, NULL)) != EOF) {
78 #ifdef CONFIG_FEATURE_IPCALC_FANCY
89 if (mode & (BROADCAST | NETWORK)) {
90 if (argc - optind > 2) {
94 if (argc - optind != 1) {
99 ipaddr = inet_addr(argv[optind]);
101 if (ipaddr == INADDR_NONE) {
102 IPCALC_MSG(error_msg_and_die("bad IP address: %s\n", argv[optind]),
107 if (argc - optind == 2) {
108 netmask = inet_addr(argv[optind + 1]);
111 if (ipaddr == INADDR_NONE) {
112 IPCALC_MSG(error_msg_and_die("bad netmask: %s\n", argv[optind + 1]),
116 /* JHC - If the netmask wasn't provided then calculate it */
118 netmask = get_netmask(ipaddr);
121 if (mode & NETMASK) {
122 printf("NETMASK=%s\n", inet_ntoa((*(struct in_addr *) &netmask)));
125 if (mode & BROADCAST) {
126 broadcast = (ipaddr & netmask) | ~netmask;
127 printf("BROADCAST=%s\n", inet_ntoa((*(struct in_addr *) &broadcast)));
130 if (mode & NETWORK) {
131 network = ipaddr & netmask;
132 printf("NETWORK=%s\n", inet_ntoa((*(struct in_addr *) &network)));
134 #ifdef CONFIG_FEATURE_IPCALC_FANCY
135 if (mode & HOSTNAME) {
136 struct hostent *hostinfo;
139 hostinfo = gethostbyaddr((char *) &ipaddr, sizeof(ipaddr), AF_INET);
141 IPCALC_MSG(error_msg("cannot find hostname for %s", argv[optind]);
143 putc('\n', stderr);,);
146 for (x = 0; hostinfo->h_name[x]; x++) {
147 hostinfo->h_name[x] = tolower(hostinfo->h_name[x]);
150 printf("HOSTNAME=%s\n", hostinfo->h_name);
160 c-file-style: "linux"