#include #include #include #include int main(int argc, char **argv) { in_addr_t ip; in_addr_t i; in_addr_t netmask; in_addr_t network; in_addr_t broadcast; int netbits; /* how many network bits */ int hostbits; /* how many host bits */ struct hostent *p; char buffer[INET_ADDRSTRLEN]; if (argc != 3) { fprintf(stderr, "%s: requires 2 arguments: IP netbits\n", argv[0]); return 1; } if (inet_pton(AF_INET, argv[1], &ip) != 1) { fprintf(stderr, "%s: first argument %s must be a dotted IPv4 address\n", argv[0], argv[1]); return 2; } i = ntohl(ip); netbits = strtol(argv[2], NULL, 10); /* string to long */ if (netbits <= 0 || netbits > 30) { fprintf(stderr, "%s: second argument %s must be number of network bits\n", argv[0], argv[2]); return 3; } hostbits = 32 - netbits; /* The netmask is netbits 1's, followed by hostbits 0's. */ netmask = -1 << hostbits; /* The network address is the IP address, with all the host bits turned off. */ network = i & netmask; /* The broadcast address is the IP address, with all the host bits turned on. */ broadcast = i | ~netmask; for (i = network + 1; i < broadcast; ++i) { ip = htonl(i); p = gethostbyaddr((char *)&ip, sizeof ip, AF_INET); if (p != NULL) { if (inet_ntop(AF_INET, &ip, buffer, sizeof buffer) != buffer) { fprintf(stderr, "%s: inet_ntop failed\n", argv[0]); return 4; } printf("%s %s\n", buffer, p->h_name); } } return EXIT_SUCCESS; }