【问题标题】:Best way to get the Network Cost on .Net Core 2.0在 .Net Core 2.0 上获取网络成本的最佳方法
【发布时间】:2026-02-15 14:55:01
【问题描述】:

有没有办法找出 .Net Core 2.0 上的网络成本?
这就是我在 C++ 代码中获取网络成本的方式:

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:
    }
}

.Net Core (2.0) 具有的一件事是 NetworkInterfaceType (https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterfacetype?view=netcore-1.0)

根据 NetworkInterfaceType,我可以查看它是否有 wifi、网络或移动连接,但这不会转化为成本。
有没有办法找出 .Net Core 2.0 的网络成本?

【问题讨论】:

  • 在您的 C++ 示例中,pNetworkCostManager 来自哪里?
  • 您是否要确定计量使用与无限制使用(即金钱)?或者,您是否尝试确定性能(速度位/秒)?
  • @SqlSurfer 计量与无限制

标签: .net .net-core .net-standard


【解决方案1】:

要调用GetCost,您必须使用COM 接口。如果您需要准确地进行此调用,即将NULL而不是IP地址传递给GetCost,那么您必须自己定义COM接口以满足您的需求,例如像这样:

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);
}

那么你可以这样获取费用信息:

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

如果您没有将NULL 传递给GetCost 的要求,您只需添加对COM 类型库“网络列表管理器1.0 类型库”的引用,将“嵌入互操作类型”设置为falseuse those definitions

【讨论】: