bj chrome
bj chrome

Reputation: 85

How to programmatically obtain adapter's IPv4/6 interface metric on Windows using C/C++ APIs?

On Win10 I can run get-netinterface in powershell to display InterfaceMetric for each interface. Is there a C/C++ Win API that would let me retrieve it programmatically?

The metric can be set in adapter's TCP/IP settings:

enter image description here

Upvotes: 2

Views: 767

Answers (2)

dragonfly
dragonfly

Reputation: 1201

Win32 has provided these APIs for you.

Please refer to these APIs, eg: GetIpForwardTable

https://learn.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-getipforwardtable2

These APIs can get and modify router info, it is just designed for your requirements.

Codes for modify metrics like this:

    MIB_IPINTERFACE_ROW entry_row;
    InitializeIpInterfaceEntry(&entry_row);
    entry_row.InterfaceIndex = index1_;
    entry_row.Family = AF_INET;
    int ret = GetIpInterfaceEntry(&entry_row);
    if (ret != NO_ERROR) {
        log_info("GetIpInterfaceEntry ret:%d:", ret);
        return ret;
    }
    entry_row.Metric = m1;
    entry_row.UseAutomaticMetric = false;
    entry_row.SitePrefixLength = 0;
    int api_ret = SetIpInterfaceEntry(&entry_row);

Upvotes: 2

Remy Lebeau
Remy Lebeau

Reputation: 595349

Is there a C/C++ Win API that would let me retrieve [InterfaceMetric] programmatically?

Use GetAdaptersAddresses(). See the Ipv4Metric and Ipv6Metric members of the IP_ADAPTER_ADDRESSES struct.

Upvotes: 1

Related Questions