Created
June 18, 2023 18:23
-
-
Save kbridge/0eebe78049e742651ebd8d21ff616234 to your computer and use it in GitHub Desktop.
demonstrate getifaddrs()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <linux/if_packet.h> | |
| #include <net/if.h> | |
| #include <netdb.h> | |
| #include <sys/socket.h> | |
| #include <sys/types.h> | |
| #include <ifaddrs.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| int | |
| main(void) | |
| { | |
| struct ifaddrs *addrs = NULL; | |
| struct ifaddrs *entry = NULL; | |
| if (getifaddrs(&addrs) < 0) { | |
| perror("getifaddrs"); | |
| exit(1); | |
| } | |
| for (entry = addrs; entry != NULL; entry = entry->ifa_next) { | |
| printf("---\n"); | |
| printf("name: %s\n", entry->ifa_name); | |
| { | |
| printf("flags: "); | |
| if (entry->ifa_flags & IFF_UP) { | |
| printf(" IFF_UP"); | |
| } | |
| if (entry->ifa_flags & IFF_RUNNING) { | |
| printf(" IFF_RUNNING"); | |
| } | |
| if (entry->ifa_flags & IFF_LOOPBACK) { | |
| printf(" IFF_LOOPBACK"); | |
| } | |
| printf("\n"); | |
| } | |
| { | |
| const char *family; | |
| if (entry->ifa_addr->sa_family == AF_INET6) { | |
| family = "AF_INET6"; | |
| } else if (entry->ifa_addr->sa_family == AF_INET) { | |
| family = "AF_INET"; | |
| } else if (entry->ifa_addr->sa_family == AF_PACKET) { | |
| family = "AF_PACKET"; | |
| } else { | |
| family = "(unknown)"; | |
| } | |
| printf("family: %s\n", family); | |
| } | |
| if (entry->ifa_addr->sa_family == AF_INET || entry->ifa_addr->sa_family == AF_INET6) { | |
| char host[NI_MAXHOST]; | |
| int result = getnameinfo( | |
| entry->ifa_addr, | |
| entry->ifa_addr->sa_family == AF_INET ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), | |
| host, | |
| NI_MAXHOST, | |
| NULL, | |
| 0, | |
| NI_NUMERICHOST); | |
| if (result != 0) { | |
| fprintf(stderr, "getnameinfo: %s\n", gai_strerror(result)); | |
| exit(1); | |
| } | |
| printf("address: %s\n", host); | |
| } else if (entry->ifa_addr->sa_family == AF_PACKET) { | |
| struct sockaddr_ll *sll = (struct sockaddr_ll *) entry->ifa_addr; | |
| unsigned char *mac = sll->sll_addr; | |
| printf("mac: %02x:%02x:%02x:%02x:%02x:%02x\n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); | |
| } | |
| } | |
| freeifaddrs(addrs); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment