Skip to content

Instantly share code, notes, and snippets.

@ngn999
Last active December 22, 2015 19:29
Show Gist options
  • Save ngn999/6519668 to your computer and use it in GitHub Desktop.
Save ngn999/6519668 to your computer and use it in GitHub Desktop.
get host ip
#include <sys/types.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <arpa/inet.h>
bool getIP(string &ip)
{
struct ifaddrs *ifa_buf = NULL; /// /usr/include/ifaddrs.h
struct ifaddrs *ifa_iter = NULL;
void *tmp_addr_ptr = NULL;
getifaddrs(&ifa_buf);
for (ifa_iter = ifa_buf; ifa_iter != NULL; ifa_iter = ifa_iter->ifa_next) {
if (ifa_iter->ifa_addr->sa_family == AF_INET) { // IPv4
tmp_addr_ptr = &((struct sockaddr_in*)ifa_iter->ifa_addr)->sin_addr;
char host_buffer[INET_ADDRSTRLEN];
inet_ntop(AF_INET, tmp_addr_ptr, host_buffer, INET_ADDRSTRLEN);
if (strncmp(host_buffer, "127.0.0.1",sizeof("127.0.0.1")) == 0)
continue;
ip.assign(host_buffer);
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment