Created
July 13, 2011 12:53
-
-
Save sbz/1080237 to your computer and use it in GitHub Desktop.
retrieve INET4 interfaces address 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 <stdlib.h> | |
#include <arpa/inet.h> | |
#include <ifaddrs.h> | |
#include <net/if.h> | |
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
int | |
main(void) { | |
struct ifaddrs *addrs = NULL; | |
struct ifaddrs *addr = NULL; | |
char buf[64]; | |
struct sockaddr_in *inet4; | |
if (getifaddrs(&addrs) == -1) { | |
perror("getifaddrs"); | |
exit(1); | |
} | |
for (addr = addrs; addr; addr = addr->ifa_next) { | |
if (addr->ifa_addr == NULL) | |
continue; | |
if ((addr->ifa_flags & IFF_UP) == 0) | |
continue; | |
if (addr->ifa_addr->sa_family != AF_INET) | |
continue; | |
inet4 = (struct sockaddr_in *)addr->ifa_addr; | |
if (inet_ntop(addr->ifa_addr->sa_family, (void *)&(inet4->sin_addr), buf, sizeof(buf)) == NULL) { | |
perror("inet_ntop inet4"); | |
exit(1); | |
} | |
printf("%s %s\n", addr->ifa_name, buf); | |
} | |
freeifaddrs(addrs); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment