Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.