title: How to get my non-loopback network ip address in C?
body: <p>For a communication between two hosts, I need to send the IP address of my host to the other site. The problem is that if I request my IP address, it might be that I get back my local loopback IP addres (127.x.x.x) , not the network (ethernet) IP address.</p>
  
  <p>I use the following code:</p>
  
  <pre><code>char myhostname[32];
  
  
  gethostname(myhostname, 32);
  hp = gethostbyname(myhostname);
  unsigned my_ip = *(unsigned*)(hp-&gt;h_addr);
  
  if( (my_ip % 256) == 127) {
    /* Wrong IP adress as it's 127.x.x.x */
    printf("Error, local IP address!");
    return;
  }
  </code></pre>
  
  <p>The only way to solve it is to make sure my hostname in /etc/hosts is behind the real network address, not the local loopback (the default for e.g. Ubuntu).</p>
  
  <p>Is there a way to solve this without relying on the content of /etc/hosts?</p>
  
  <p><strong>Edit:</strong> I changed the above code so it makes use of getaddrinfo, but I still get back the loopback device's number (127.0,0,1) instead of the real IP address:</p>
  
  <pre><code>struct addrinfo hint = {0};
  struct addrinfo *aip = NULL;
  unsigned ip = 0;
  struct sockaddr_in *sinp = NULL;
  
  hint.ai_family = AF_INET; /* IPv4 */
  hint.ai_socktype = SOCK_STREAM;
  
  if(getaddrinfo(hostname, NULL, &amp;hint, &amp;aip) != 0) {
      return 0;
  }
  sinp = (struct sockaddr_in *) aip-&gt;ai_addr;
  ip   = *(unsigned *) &amp;sinp-&gt;sin_addr;
  </code></pre>
  
  <p>(I used to get back a list of 3 addrinfo's with the three SOCK_STREAM,SOCK_DGRAM and SOCK_RAW, but the hint prevents that)</p>
  
  <p>So my question still stands...</p>