title: Get Local Ip address in c++
body: <p>I have a code to get local ip address. This is the code I use.</p>
  
  <pre><code>typedef std::map&lt;string,string&gt; settings_t;
  
  void loadLocalIp (settings_t &amp;ipConfig)
  {
      struct ifaddrs * ifAddrStruct=NULL;
      struct ifaddrs * ifa=NULL;
      void * tmpAddrPtr=NULL;      
  
      getifaddrs(&amp;ifAddrStruct);
  
      for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa-&gt;ifa_next) {
          if (ifa -&gt;ifa_addr-&gt;sa_family==AF_INET) { // check it is IP4
              // is a valid IP4 Address
              tmpAddrPtr=&amp;((struct sockaddr_in *)ifa-&gt;ifa_addr)-&gt;sin_addr;
              char addressBuffer[INET_ADDRSTRLEN];
              inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
  
              string key(ifa-&gt;ifa_name);
              string value(addressBuffer);
              cout&lt;&lt;key&lt;&lt;" =1 " &lt;&lt;value&lt;&lt;endl;
              ipConfig.insert(std::pair&lt;string,string&gt;(key, value));
  
             // printf("'%s': %s\n", ifa-&gt;ifa_name, addressBuffer); 
           }
       }
      if (ifAddrStruct!=NULL) 
          freeifaddrs(ifAddrStruct);//remember to free ifAddrStruct
  }
  
  int main()
  {
      settings_t ipConfig;
      loadLocalIp(ipConfig);
      cout&lt;&lt;ipConfig.at("enp2s0")&lt;&lt;endl;
      return 0;
  }
  </code></pre>
  
  <p>So My result, is </p>
  
  <pre><code>lo =1 127.0.0.1
  enp2s0 =1 172.20.55.6
  172.20.55.6
  </code></pre>
  
  <p>But In another computer, the interface name is different. They get result like bellow,</p>
  
  <pre><code>lo =1 127.0.0.1
  ens32 =1 172.20.55.9
  terminate called after throwing an instance of 'std::out_of_range'
    what():  map::at
  Aborted (core dumped)
  </code></pre>
  
  <p>I want to get my Ip address whatever the interface name is. How can I get my local ip address if the interface name varies from different computer. It should give the ip address whatever the interface name is. How can I do this?</p>
  
  <p>My question is, Now I am getting my local IP from this method. But I should get IP whatever the Interface name is. One thing, I need to find that interface name and apply it in my above code (or) Is there any other option to find that IP without that interface? </p>