I am trying to read IP address in ubuntu system using C code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv) {
int status;
struct addrinfo hints, *p;
struct addrinfo *servinfo;
char ipstr[INET_ADDRSTRLEN];
char hostname[128];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
gethostname(hostname, 128);
if ((status = getaddrinfo(hostname, NULL, &hints, &servinfo)) == -1) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
for (p=servinfo; p!=NULL; p=p->ai_next) {
struct in_addr *addr;
if (p->ai_family == AF_INET) {
struct sockaddr_in *ipv = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv->sin_addr);
}
else {
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = (struct in_addr *) &(ipv6->sin6_addr);
}
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
}
printf("Address: %s\n", ipstr);
freeaddrinfo(servinfo);
return 0;
}
I am not getting actual client IP instead I am getting 127.0.1.1 whereas I was expecting 192.168.x.x When I comment 127.0.1.1 in /etc/hosts file I get the actual IP but this solution is not feasible