Created
August 31, 2015 21:35
-
-
Save icedraco/68e8be949ca4bf6d04ec to your computer and use it in GitHub Desktop.
Obtaining network device details using getifaddrs(3)
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 <stdio.h> | |
| #include <stdint.h> | |
| #include <ifaddrs.h> | |
| #include <netdb.h> | |
| int main(int argc, char** argv) { | |
| struct ifaddrs* addrs; | |
| struct ifaddrs* ifa; | |
| if (getifaddrs(&addrs) < 0) { | |
| perror("getifaddrs"); | |
| return 1; | |
| } | |
| // For human-readable IP addresses | |
| char host[NI_MAXHOST]; | |
| char hostDest[NI_MAXHOST]; | |
| char netmask[NI_MAXHOST]; | |
| for (ifa = addrs; ifa; ifa = ifa->ifa_next) { | |
| if (ifa->ifa_addr == NULL) | |
| continue; | |
| if (ifa->ifa_addr->sa_family != AF_INET) | |
| continue; | |
| // Extract human-readable IP addresses | |
| if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) < 0) { | |
| perror("getnameinfo"); | |
| continue; | |
| } | |
| if (getnameinfo(ifa->ifa_dstaddr, sizeof(struct sockaddr_in), hostDest, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) < 0) { | |
| perror("getnameinfo"); | |
| continue; | |
| } | |
| if (getnameinfo(ifa->ifa_netmask, sizeof(struct sockaddr_in), netmask, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) < 0) { | |
| perror("getnameinfo"); | |
| continue; | |
| } | |
| // Display extracted info | |
| printf("Name: %16s\n", ifa->ifa_name); | |
| printf("Addr: %16s [%08llx]\n", host, ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr); | |
| printf("Dest: %16s [%08llx]\n", hostDest, ((struct sockaddr_in*)ifa->ifa_dstaddr)->sin_addr); | |
| printf("Mask: %16s [%08llx]\n", netmask, ((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr); | |
| printf("\n"); | |
| } | |
| freeifaddrs(addrs); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment