0

I'm writing some code that needs to retrieve the interface used to connect to internet using C++ on a windows machine (windows XP to 8) but I can not find how to do it.

I've looked at GetAdaptersInfo but i did not find a way to retrieve the adapter used to connect to internet.

Thanks in advance!

Joan P.S
  • 1,553
  • 1
  • 16
  • 42
  • This is equivalent to finding the adapter corresponding to the default route, see linked question for access to routes. – Ben Voigt Mar 09 '15 at 15:13
  • The [GetBestInterfaceEx](https://learn.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getbestinterfaceex) function retrieves the index of the interface that has the best route to the specified IPv4 or IPv6 address. So, call GetBestInterfaceEx with an 'internet' address. – CarlJohnson Jan 18 '19 at 11:07

1 Answers1

1

I don't believe there is a reliable way to do that. Since internet is essentially a collection of networks with moderate amounts of filtering in between this can fail in multiple ways (in no particular order):

  • adapter may have multiple addresses assigned some of which are limited to LAN;
  • box may have internal virtual network (virtualbox);
  • box may have multiple adapters "connected to the internet" and adapter used to connect to external services will vary from service to service;
  • your gateway may allow some services and block others;
  • adapter may be connected to LAN that is quite huge.

The only reliable way is to iterate over all addresses assigned to all adapters (maybe discarding loop-back (127.0.0.0/8) and link-local (169.254.0.0/16) addresses on the way) and attempting to connect to external service you are interested in.

friendzis
  • 799
  • 6
  • 17