Skip to content

Instantly share code, notes, and snippets.

@WoZ
Created March 23, 2018 15:07
Show Gist options
  • Save WoZ/24418163a7f595c90c6c16819cc4a183 to your computer and use it in GitHub Desktop.
Save WoZ/24418163a7f595c90c6c16819cc4a183 to your computer and use it in GitHub Desktop.
#include <arpa/inet.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <stdio.h>
int main(int argc, char* argv[], char* envp[]) {
struct ifaddrs *ifa=NULL,*ifEntry=NULL;
void *addPtr = NULL;
int rc = 0;
int family, addrLen, ret;
char addressBuffer[INET6_ADDRSTRLEN];
char hostnameBuffer[255];
rc = getifaddrs(&ifa);
if (rc == 0) {
for (ifEntry=ifa; ifEntry!=NULL; ifEntry=ifEntry->ifa_next) {
if (ifEntry->ifa_addr == NULL) {
continue;
}
if (!(ifEntry->ifa_flags & IFF_UP)) {
continue;
}
if(ifEntry->ifa_addr->sa_data == NULL) {
continue;
}
family = ifEntry->ifa_addr->sa_family;
addrLen = (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
if (family == AF_INET) {
addPtr = &((struct sockaddr_in *)ifEntry->ifa_addr)->sin_addr;
} else if(family == AF_INET6) {
addPtr = &((struct sockaddr_in6 *)ifEntry->ifa_addr)->sin6_addr;
} else {
continue;
}
const char *a = inet_ntop(family, addPtr, addressBuffer, sizeof(addressBuffer));
ret = getnameinfo(ifEntry->ifa_addr, addrLen, hostnameBuffer, sizeof(hostnameBuffer), NULL, 0, NI_NAMEREQD);
if (ret != 0) {
errx(1, "%s", gai_strerror(ret));
} else
printf("%s %s\n", addressBuffer, hostnameBuffer);
}
}
freeifaddrs(ifa);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment