| 1 | |
| 2 | #ifdef HAVE_CONFIG_H |
| 3 | #include <config.h> |
| 4 | #endif |
| 5 | |
| 6 | #include <arpa/inet.h> |
| 7 | #include <sys/socket.h> |
| 8 | #include <netinet/in.h> |
| 9 | #include <net/if.h> |
| 10 | #include <netdb.h> |
| 11 | #include <ifaddrs.h> |
| 12 | #include <stdio.h> |
| 13 | #include <stdlib.h> |
| 14 | #include <unistd.h> |
| 15 | |
| 16 | |
| 17 | int main(int argc, char *argv[]) { |
| 18 | |
| 19 | struct ifaddrs *ifaddr, *ifa; |
| 20 | int family, s; |
| 21 | char host[NI_MAXHOST], broad[NI_MAXHOST], mask[NI_MAXHOST]; |
| 22 | |
| 23 | if (getifaddrs(&ifaddr) == -1) { |
| 24 | perror("getifaddrs"); |
| 25 | exit(EXIT_FAILURE); |
| 26 | } |
| 27 | |
| 28 | for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { |
| 29 | if (ifa->ifa_addr) { |
| 30 | |
| 31 | family = ifa->ifa_addr->sa_family; |
| 32 | |
| 33 | if (family == AF_INET || family == AF_INET6) { |
| 34 | |
| 35 | printf("%s ", ifa->ifa_name); |
| 36 | |
| 37 | s = getnameinfo(ifa->ifa_addr, |
| 38 | (family == AF_INET) ? sizeof(struct sockaddr_in) : |
| 39 | sizeof(struct sockaddr_in6), |
| 40 | host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); |
| 41 | if (s != 0) { |
| 42 | fprintf(stderr, "getnameinfo() failed: %s\n", gai_strerror(s)); |
| 43 | exit(EXIT_FAILURE); |
| 44 | } |
| 45 | printf("%s ", host); |
| 46 | |
| 47 | s = getnameinfo(ifa->ifa_netmask, (family == AF_INET) ? |
| 48 | sizeof(struct sockaddr_in) : |
| 49 | sizeof(struct sockaddr_in6), mask, NI_MAXHOST, |
| 50 | NULL, 0, NI_NUMERICHOST); |
| 51 | if (s != 0) { |
| 52 | fprintf(stderr, "getnameinfo() failed: %s\n", gai_strerror(s)); |
| 53 | exit(EXIT_FAILURE); |
| 54 | } |
| 55 | printf("%s ", mask); |
| 56 | |
| 57 | if (family == AF_INET && ifa->ifa_flags & IFF_BROADCAST) { |
| 58 | s = getnameinfo(ifa->ifa_broadaddr, (family == AF_INET) ? |
| 59 | sizeof(struct sockaddr_in) : |
| 60 | sizeof(struct sockaddr_in6), broad, NI_MAXHOST, |
| 61 | NULL, 0, NI_NUMERICHOST); |
| 62 | if (s != 0) { |
| 63 | fprintf(stderr, "getnameinfo() failed: %s\n", gai_strerror(s)); |
| 64 | exit(EXIT_FAILURE); |
| 65 | } |
| 66 | printf("%s\n", broad); |
| 67 | } else |
| 68 | printf("X\n"); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | freeifaddrs(ifaddr); |
| 74 | exit(EXIT_SUCCESS); |
| 75 | } |