0

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

rac10
  • 43
  • 7
  • Have a look at this https://stackoverflow.com/a/265978. – Shubham Feb 19 '21 at 05:33
  • @shubham Thanks for looking into,the problem with getifaddr is it is not POSIX compilant – rac10 Feb 19 '21 at 05:38
  • I think, it is a lot better to use cross-platform libraries for better support, code quality and documentation, for example, Qt's sockets or boost::asio. Both provide whole lot of functionality, your request included. Writing code with raw POSIX or Winsock sockets has become somewhat... outdated, 15 years ago or so. – Leontyev Georgiy Feb 19 '21 at 07:42
  • I'm fairly sure you can't assume that getaddrinfo() will actually resolve anything for your hostname. Doesn't it work by (in effect) doing a lookup in /etc/hosts or DNS? And there's no promise either will have entries, or that it will be the one you want. – Joseph Larson Feb 19 '21 at 13:12
  • @JosephLarson When there is 127.0.1.1. entry in hosts file it gives only one entry that is 127.0.1.1.When that is commented it will provide multiple nodes – rac10 Feb 19 '21 at 13:18

0 Answers0