j0kky
j0kky

Reputation: 85

How to determine the default network adapter through WinApi?

Is there a way through Windows API to determine which is the primary/default network adapter?

For example, if I have a PC with two network cards, I need to know which one is used by the system to access internet, similarly if I have a network adapter and a virtual adapter.

I tried with GetAdaptersAddresses but it doesn't show which is the favourite one, maybe with GetBestInterface?

Upvotes: 3

Views: 4416

Answers (2)

Edward Clements
Edward Clements

Reputation: 5132

This SO Answer explains how to determine the local IP address used to connect to the Internet (like Google's DNS servers), you can then compare this local IP address with the list returned by GetAdaptersAddresses to determine which network card was used for Internet Access.

Upvotes: 2

kvr
kvr

Reputation: 573

How about using GetAdaptersInfo and looking for an IP range that satisfies your requirement?

Alternatively, came across this (WMI):

https://msdn.microsoft.com/en-us/library/windows/desktop/aa394216(v=vs.85).aspx

~snip:

Once you have done so, you will likely have reduced your list to one or two configured adapters.

You can also use the following procedure to find the default adapter:

  1. Run the following query: "SELECT InterfaceIndex, Destination FROM Win32_IP4RouteTable WHERE Destination='0.0.0.0'" You should only have one default network destination 0.0.0.0.
  2. Use the InterfaceIndex to retrieve the Network Adapter you want. "SELECT * FROM Win32_NetworkAdapter WHERE InterfaceIndex=" + insertVariableHere

Here's a CodeProject article claiming to determine the default:

http://www.codeproject.com/Articles/13421/Getting-the-Physical-MAC-address-of-a-Network-Inte

Getting the Physical (MAC) address of a Network Interface Card and finding out if it is the primary adapter on a multi-homed system

Finding out if the adapter with the given index is the primary adapter In order to find out if the adapter with the given index is the primary adapter, I had to add a function to the dialog class CNetCfgDlg. This code iterates over the m_pAdapters array, comparing the given adapter index with the index for each adapter in the array. If the given adapter index is equal to the smallest index of all adapters in the array, then it is the primary adapter

And one more thing to consider, is there's the 'Automatic Metric' setting for each adapter which seems to choose the lowest setting as the preferred (although not sure how to access this metric setting programmatically):

http://www.softminer.net/2011/09/setting-default-network-adapter-in.html

Upvotes: 4

Related Questions