Created
October 27, 2015 04:49
-
-
Save nczz/b052b2fc78498298f44f to your computer and use it in GitHub Desktop.
Linux_Get_IP_Address(IPv4 & IPv6) ref: http://stackoverflow.com/questions/212528/get-the-ip-address-of-the-machine
This file contains 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 <sys/types.h> | |
#include <ifaddrs.h> | |
#include <netinet/in.h> | |
#include <string.h> | |
#include <arpa/inet.h> | |
int main (int argc, const char * argv[]) { | |
struct ifaddrs * ifAddrStruct=NULL; | |
struct ifaddrs * ifa=NULL; | |
void * tmpAddrPtr=NULL; | |
getifaddrs(&ifAddrStruct); | |
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { | |
if (!ifa->ifa_addr) { | |
continue; | |
} | |
if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4 | |
// is a valid IP4 Address | |
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr; | |
char addressBuffer[INET_ADDRSTRLEN]; | |
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); | |
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); | |
} else if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6 | |
// is a valid IP6 Address | |
tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr; | |
char addressBuffer[INET6_ADDRSTRLEN]; | |
inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); | |
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); | |
} | |
} | |
if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment