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)
46 unsigned long netmask = 0;
47 unsigned long broadcast;
48 unsigned long network;
51 static const struct option long_options[] = {
52 {"netmask", no_argument, NULL, 'n'},
53 {"broadcast", no_argument, NULL, 'b'},
54 {"network", no_argument, NULL, 'w'},
55 #ifdef CONFIG_FEATURE_IPCALC_FANCY
56 {"hostname", no_argument, NULL, 'h'},
57 {"silent", no_argument, NULL, 's'},
62 bb_applet_long_options = long_options;
63 mode = bb_getopt_ulflags(argc, argv,
64 #ifdef CONFIG_FEATURE_IPCALC_FANCY
69 if (mode & (BROADCAST | NETWORK)) {
70 if (argc - optind > 2) {
74 if (argc - optind != 1) {
79 ipaddr = inet_addr(argv[optind]);
81 if (ipaddr == INADDR_NONE) {
82 IPCALC_MSG(bb_error_msg_and_die("bad IP address: %s", argv[optind]),
87 if (argc - optind == 2) {
88 netmask = inet_addr(argv[optind + 1]);
91 if (ipaddr == INADDR_NONE) {
92 IPCALC_MSG(bb_error_msg_and_die("bad netmask: %s", argv[optind + 1]),
96 /* JHC - If the netmask wasn't provided then calculate it */
98 netmask = get_netmask(ipaddr);
101 if (mode & NETMASK) {
102 printf("NETMASK=%s\n", inet_ntoa((*(struct in_addr *) &netmask)));
105 if (mode & BROADCAST) {
106 broadcast = (ipaddr & netmask) | ~netmask;
107 printf("BROADCAST=%s\n", inet_ntoa((*(struct in_addr *) &broadcast)));
110 if (mode & NETWORK) {
111 network = ipaddr & netmask;
112 printf("NETWORK=%s\n", inet_ntoa((*(struct in_addr *) &network)));
114 #ifdef CONFIG_FEATURE_IPCALC_FANCY
115 if (mode & HOSTNAME) {
116 struct hostent *hostinfo;
119 hostinfo = gethostbyaddr((char *) &ipaddr, sizeof(ipaddr), AF_INET);
121 IPCALC_MSG(bb_herror_msg_and_die(
122 "cannot find hostname for %s", argv[optind]),);
125 for (x = 0; hostinfo->h_name[x]; x++) {
126 hostinfo->h_name[x] = tolower(hostinfo->h_name[x]);
129 printf("HOSTNAME=%s\n", hostinfo->h_name);
139 c-file-style: "linux"