#include #include #include #include #include #include #include #include int main(int argc, char **argv) { const int s = socket(AF_INET, SOCK_DGRAM, 0); struct ifconf ifc; const struct ifreq *p; const size_t guess = 100; /* hope no more than this # of interfaces */ size_t n; /* actual number of interfaces */ if (s < 0) { perror(argv[0]); return 1; } ifc.ifc_len = guess * sizeof (struct ifreq); ifc.ifc_buf = malloc(ifc.ifc_len); if (ifc.ifc_buf == NULL) { perror(argv[0]); return 2; } if (ioctl(s, SIOCGIFCONF, &ifc) < 0) { perror(argv[0]); return 3; } n = ifc.ifc_len / sizeof (struct ifreq); if (n > guess) { fprintf(stderr, "%s: increase guess to at least %d and try again.\n", argv[0], n); return 4; } for (p = ifc.ifc_req; p < ifc.ifc_req + n; ++p) { const struct sockaddr_in *const address = (struct sockaddr_in *)&p->ifr_addr; char dotted[INET6_ADDRSTRLEN]; if (inet_ntop(address->sin_family, &address->sin_addr, dotted, sizeof dotted) == NULL) { fprintf(stderr, "%s: inet_ntop failed\n", argv[0]); return 5; } printf("%s %d %s\n", p->ifr_name, address->sin_family, dotted); } return EXIT_SUCCESS; }