Background:
I'm writing a daemon that makes outgoing TCP/IP connections. It will be running on machines with multiple (non-loopback) IP addresses. I'd like the users to be able to specify, in the daemon's config file, which IP address(es) to use for outgoing connections, or *
to use all.
The addresses will be used in a rotation, each connection going out from the IP address used least recently. This behavior is important, as is *
being a replacement for "all" so daemons running on multiple machines can point to the same config file on a fileshare, and have each use its own set of IP addresses.
Problem:
How do I get a list of all the IP addresses a machine can make outgoing (i.e. to any other computer) connections on? Given a list of all IP addresses, how would I filter out loopback addresses?
I'm in C, and if possible I'd like to use POSIX only, but the daemon will probably only ever run on Linux boxes, so I'd accept a Linux-centric answer.
Each IP address will be available on exactly one (possibly virtual) network device and vice versa, so a way to enumerate network devices and get associated IP addresses would also suffice, though I wouldn't really be happy about it. (Side questions: Is it even possible to associate multiple IP addresses with a single device? How 'bout the same IP under multiple devices? Not important.)
Insufficient Solutions:
gethostname()
/gethostbyname()
(as this question). Using that method, I only ever get 127.0.0.1 back (or .1.1 in Debian). I suspect this is because the hostname of the machine is in thehosts
file, and that's as far asgethostbyname()
checks. (I believe that's why in Debian I always get 127.0.1.1: Debian defaults to adding localhost as 127.0.0.1 and the machine's hostname as 127.0.1.1 to thehosts
file, right?) I'd like a solution that ignoreshosts
and gives me everything actually there.- I've had no more luck with
getaddrinfo()
thangethostname()
/gethostbyname()
. It seems to be bound by the same problem. I tested this passing the machine's hostname and aNULL
service (port) into it; the docs say passing aNULL
hostname AND aNULL
service is illegal, and this is backed up by testing. Not sure how else to ask it for everything on the machine, but I'm open to suggestions in this vein. - EDIT: this answer shows how to get the IP address from a device name, but doesn't show how to enumerate the device names. Any ideas?
FINAL EDIT: I've accepted caskey's answer to give him the credit for pointing me in the direction of how this needs to be done. I've posted my own answer listing the source code of how exactly to do it in case anyone else needs it.