【问题标题】:How can I tell if the connection is metered?如何判断连接是否按流量计费?
【发布时间】:2013-04-20 16:10:03
【问题描述】:

我编写了一个监控 IMAP 电子邮件帐户的程序。它按计划运行,在我旅行的笔记本电脑上运行。有时,当我的互联网连接通过我的移动设备连接时,它会运行,该设备具有计量连接(即我按 GB 付费),但我不希望它这样做,因为它使用大量带宽,而且它可以等待直到带宽可用。

所以问题是:.NET 程序如何确定其使用的连接何时被计量?

【问题讨论】:

  • 这是 Windows 8 吗?我认为 Windows 8 有一个“计量”属性,您可以在连接上设置,但我在 7 或更早版本上没有看到它。
  • 考虑到任意网络连接,如果可以做到这一点,我会感到非常惊讶。
  • @Rup:这不是 Windows 业务。不像它联系 ISP 并询问链接类型。
  • @Xaqron 但 Windows 知道它是使用 wifi 还是使用 USB 调制解调器,这就是他要问的。为什么需要询问 ISP?
  • 没想到这么复杂。在 Windows 8 中,您可以手动指定对连接进行计量。该标志必须存储在某处,并通过 API 或直接注册表读取来读取。我不是想建立一个使用启发式或任何东西,只是阅读手动设置。

标签: .net windows network-programming


【解决方案1】:

简单搜索 MSDN 发现 NetworkInformation.GetInternetConnectionProfile 函数。它看起来像是 Metro 界面的正式一部分,但我听说桌面应用程序可以访问大多数 Metro 库。

【讨论】:

    【解决方案2】:

    在 2021 年,您可以使用 powershell .NET 框架和类似的注册 KEY 来测试您的以太网连接是否设置为计量:

    $definition = @"
    using System;
    using System.Runtime.InteropServices;
    
    namespace Win32Api
    {
    
        public class NtDll
        {
            [DllImport("ntdll.dll", EntryPoint="RtlAdjustPrivilege")]
            public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool Enabled);
        }
    }
    "@
    
    Add-Type -TypeDefinition $definition -PassThru | Out-Null
    [Win32Api.NtDll]::RtlAdjustPrivilege(9, $true, $false, [ref]$false) | Out-Null
    
    #Setting ownership to Administrators
    $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
    $acl = $key.GetAccessControl()
    # Use your account "Administrators" or any other which is actually an existing one on your account
    $acl.SetOwner([System.Security.Principal.NTAccount]"Administrators")
    $key.SetAccessControl($acl)
    
    #Giving Administrators full control to the key
    $rule = New-Object System.Security.AccessControl.RegistryAccessRule ([System.Security.Principal.NTAccount]"Administrators","FullControl","Allow")
    $acl.SetAccessRule($rule)
    $key.SetAccessControl($acl)
    $path = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost"
    # you can check for "Ethernet" "Wifi" "4G" etc.
    $name = "Ethernet"
    #If the Value is 2 = metered
    New-ItemProperty -Path $path -Name $name -Value "2" -PropertyType DWORD -Force | Out-Null
    

    如果出现以下错误:

    Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated.".
    

    尝试将“管理员”用户更改为您帐户中存在且具有管理员权限的任何其他用户。

    【讨论】:

    • 嗯,恭喜您找到了解决方案,但我不喜欢必须更改注册表权限的想法。一定有其他方法可以找到它。
    猜你喜欢
    • 2011-10-23
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多