Skip to content

Instantly share code, notes, and snippets.

@oneamtu
Created June 17, 2011 19:13
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 oneamtu/1032081 to your computer and use it in GitHub Desktop.
Save oneamtu/1032081 to your computer and use it in GitHub Desktop.
Fastest way to obtain IP address of current host
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/time.h>
using namespace std;
int main(int argc, char** argv) {
struct ifaddrs * ifAddrStruct=NULL;
struct ifaddrs * ifa=NULL;
void * tmpAddrPtr=NULL;
getifaddrs(&ifAddrStruct);
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
char addressBuffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
if (!strcmp("eth0", ifa->ifa_name)) {
printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment