Last active
December 17, 2015 13:39
-
-
Save qxj/5618237 to your computer and use it in GitHub Desktop.
Get IP address of local network interface by 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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <string.h> | |
#include <netdb.h> | |
#include <ifaddrs.h> | |
#include <arpa/inet.h> | |
#include <sys/socket.h> | |
int main(int argc, char *argv[]) | |
{ | |
const char* ifname = "eth0"; | |
struct ifaddrs *ifaddr, *ifa; | |
if(argc > 1){ | |
ifname = argv[1]; | |
}else{ | |
printf("Usage:\n\t%s <eth?>\n", argv[0]); | |
exit(0); | |
} | |
if (getifaddrs(&ifaddr) == -1) { | |
perror("getifaddrs"); | |
exit(EXIT_FAILURE); | |
} | |
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { | |
if((ifa->ifa_addr != NULL) && | |
(strcmp(ifa->ifa_name, ifname) == 0) && | |
(ifa->ifa_addr->sa_family == AF_INET)) { | |
printf("\tInterface: <%s>\n",ifa->ifa_name ); | |
printf("\tAddress: <%s>\n", inet_ntoa(((struct sockaddr_in *)ifa->ifa_addr)->sin_addr)); | |
break; | |
} | |
} | |
freeifaddrs(ifaddr); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment