Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get the Network Cost on .Net Core 2.0

Is there a way of finding out the Network cost on .Net Core 2.0?
This is how I get the Network cost in my c++ code:

hr = pNetworkCostManager->GetCost(&dwCost, NULL);
if (hr == S_OK) {
    switch (dwCost) {
    case NLM_CONNECTION_COST_UNRESTRICTED:  
    case NLM_CONNECTION_COST_FIXED:         
    case NLM_CONNECTION_COST_VARIABLE:      
    case NLM_CONNECTION_COST_OVERDATALIMIT: 
    case NLM_CONNECTION_COST_CONGESTED:    
    case NLM_CONNECTION_COST_ROAMING:     
    case NLM_CONNECTION_COST_APPROACHINGDATALIMIT:
    case NLM_CONNECTION_COST_UNKNOWN:
    }
}

One thing that .Net Core (2.0) has is NetworkInterfaceType (https://learn.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterfacetype?view=netcore-1.0)

Based on the NetworkInterfaceType I can see if it has wifi, network or mobile connection but that will not translate to a cost.
Is there any way finding out the Network cost on .Net Core 2.0?

like image 402
Mark Avatar asked Oct 17 '22 05:10

Mark


1 Answers

To call GetCost you will have to use the COM interface. If you need to make exactly this call, i.e. pass NULL instead of an IP address into GetCost, then you will have to define the COM interface on your own to satisfy your needs, e.g. like this:

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[ComImport, Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B"), ClassInterface(ClassInterfaceType.None)]
public class NetworkListManager : INetworkCostManager
{
    [MethodImpl(MethodImplOptions.InternalCall)]
    public virtual extern void GetCost(out uint pCost, [In] IntPtr pDestIPAddr);
}


[ComImport, Guid("DCB00008-570F-4A9B-8D69-199FDBA5723B"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface INetworkCostManager
{
    void GetCost(out uint pCost, [In] IntPtr pDestIPAddr);
}

Then you can obtain the cost information like this:

new NetworkListManager().GetCost(out uint cost, IntPtr.Zero);

If you don't have the requirement of passing NULL into GetCost you can simply add a reference to the COM type library "Network List Manager 1.0 Type Library", set "Embed Interop Types" to false and use those definitions.

like image 127
martin_joerg Avatar answered Oct 21 '22 05:10

martin_joerg