Reputation: 18776
I'm working on a machine that has multiple local network interfaces. Each interface is on a distinct network: for example, en0
might be 10.0.0.x
, en1
192.168.1.x
, etc.
I'd like to programatically answer the question: "Which interface is likely to be able to get to the given local IP address?"
For instance, if I wanted to talk to 10.0.0.75
, that would be en0
, 192.168.1.4
would be en1
. I'm sure there's a smarter way to do this than manually comparing IP address fragments.
Bonus points if this works on iOS as well as Mac OS X - iOS does support multiple local interfaces, even if it's rare.
Upvotes: 2
Views: 506
Reputation: 2979
The approach I'd consider is to enumerate all the configured interfaces and get their IP-address and netmask. You can then calculate the Hostmin and Hostmax for that subnet, if your candidate falls within the Hostmax-Hostmin IP-range this host should be reachable directly on the local subnet of that interface.
You can find an online tool for these types of calculations at http://jodies.de/ipcalc. It's fairly straightforward bit-operations to do these calculations programatically.
There are IP-address functions you can use in arpa/inet.h
, inet_addr
for instance will give you a 32-bit value from a dotted-decimals formatted IP-address.
Upvotes: 1