UNIX, Get local IP Address with C / C++

A few years ago Matt Oates gave me some useful C code to query the network interfaces on a unix machine for the IP addresses in use.  Here it is with a little bit of C++:


getLocalIP.h
 #ifndef _GETLOCALIP_H  
 #define _GETLOCALIP_H  
   
     #include <iostream>  
     #include <string>  
     #include <vector>  
   
     #include <net/if.h>    //for network interfaces  
     #include <arpa/inet.h>    // for get hostbyname  
     #include <sys/ioctl.h>    // to talk to interface  
     #include <unistd.h>      // for close()  
   
     // Modifies the vector specified in the argument  
     bool getLocalIP( std::vector<std::string> &addresses );  
   
 #endif  



getLocalIP.cc
   
 #include "getLocalIP.h"  
   
 // Modifies the vector specified in the argument  
 bool getLocalIP( std::vector<std::string> &addresses ) {  
   
     int sockDesc;  
     struct ifconf ifc;  
     struct ifreq *ifr, ifreqbuf[32];  
     struct sockaddr_in *sin;  
     int n;  
     char ip[ INET_ADDRSTRLEN ];  
   
     sockDesc = socket(AF_INET, SOCK_DGRAM,0);  
     if( sockDesc < 0 ) {  
         std::cout << " Cannot open socket " << std::endl;  
         return false;  
     }  
   
     ifc.ifc_req = ifreqbuf;  
     ifc.ifc_len = sizeof( ifreqbuf );  
   
     // Make a call to get a list of all network interface records  
     ioctl( sockDesc, SIOCGIFCONF, &ifc );  
   
     // Work out the number of records  
     n = ifc.ifc_len / sizeof( struct ifreq );  
   
     if( n <= 0 ) {  
         close( sockDesc );  
         return false;  
     }  
   
     // While there are still records, save to our string vector.  
     for( ifr = ifc.ifc_req; n > 0; n--, ifr++ ) {  
           
         // ignore non IPv4 records  
         if( ifr->ifr_addr.sa_family != AF_INET ) continue;  
   
         // Soure internet address is?  
         sin = (struct sockaddr_in *) &ifr->ifr_addr;  
         inet_ntop( AF_INET, (void*)&sin->sin_addr, ip, INET_ADDRSTRLEN);  
           
         addresses.push_back( ip );  
   
     }  
   
     close(sockDesc);  
     return true;  
 }  
   
   



And a usage example, main.cc:
 #include <iostream>  
 #include <string>  
 #include <vector>  
 #include "getLocalIP.h"  
   
 int main(void) {  
   
     std::vector<std::string> ipAdds;  
     if( !( getLocalIP( ipAdds ) ) ) {  
         std::cout << " Failed to get local IP addresses." << std::endl;  
     }  
   
     std::vector<std::string>::const_iterator it;  
     it = ipAdds.begin();  
     while( it != ipAdds.end() ) {  
         std::cout << (*it) << std::endl;  
         it++;  
     }  
     return 0;  
 }