I’m trying to retrieve the IP Address of the local machine in my program. The Operating System is Ubuntu 8.10. I tried using gethostname() and gethostbyname() to retrieve the IP Address. The answer I received is 127.0.1.1. I learned that it seems to be a Debian thing: The document linked here explained the idea.
The content of my /etc/hosts file is:
127.0.0.1 localhost
127.0.1.1 mymachine
In this case, is there any other way to programmatically (prefer C or C++) to get the IP Address without modifying the system file on the machine?
See ‘netdevice’, through
man netdeviceor on the web.SIOCGIFCONF can then be used to get an enumeration of all transport layer addresses.
Edit (on manpages):
manis a very useful command on Linux (or other UNIX-like systems as well). It shows a brief description of most commands, library functions, programs, etc. Open a shell prompt and typeman lsorman netdevice, and you’ll see what I mean.Edit (on general retrieving of IP): The easiest way, if you think the C way is too messy, is a simple shell script like (just from the top of my head):
ifconfig|grep 'inet addr'|awk '{print $2}'|sed 's/addr://g'Edit (on the Brain solution): What he does is using the if_nameindex() function for finding all network device names, and then the SIOCFIFCONF ioctl on each of these names for finding their IP. As he says, it only lists one IP per device.