Skip to content

Instantly share code, notes, and snippets.

@qxj
Last active December 17, 2015 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qxj/5618237 to your computer and use it in GitHub Desktop.
Save qxj/5618237 to your computer and use it in GitHub Desktop.
Get IP address of local network interface by getifaddrs().
#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