首页 > 解决方案 > 获取 netsh 显示的代理

问题描述

我正在寻找一种方法来获取 netsh 列出的代理:

C:\Windows\system32>netsh winhttp set proxy 10.0.0.6:8080
Current WinHTTP proxy settings:
    Proxy Server(s) :  10.0.0.6:8080
    Bypass List     :  (none)

C:\Windows\system32>netsh.exe winhttp show proxy
Current WinHTTP proxy settings:
    Proxy Server(s) :  10.0.0.6:8080
    Bypass List     :  (none)

所以基本上我想阅读 10.0.0.6:8080 或者如果没有设置代理

Direct access (no proxy server).

我尝试使用:

WebRequest.DefaultWebProxy;

或者

var proxy2 = System.Net.HttpWebRequest.GetSystemWebProxy();

但两者始终为空。netsh 是如何工作的,还是我首先必须尝试创建一个 Web 请求?

谢谢斯蒂芬

标签: c#.net.net-core

解决方案


似乎没有 MS 类来获取此信息,但我遇到了以下 PS 项目:https ://gist.github.com/XPlantefeve/a53a6af53b458188ee0766acc8508776

所以我花了几个小时把它翻译成 c#。我希望我没有犯任何大错误,但它似乎正在工作:

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Text;


namespace ConsoleApp1
{
    public class WinHttpProxySettings
    {

        // Source: https://gist.github.com/XPlantefeve/a53a6af53b458188ee0766acc8508776

        public enum ContextObject {

            LocalMachine,
            CurrentUser,
            LocalMachineWoW64
        }

        [Flags]
        enum MultiHue : short
        {
            None = 0,
            alwayson = 1,   // this flag is always on. it will be removed for display
            manual = 2,     // uses the 'proxy' field
            auto = 4,       // uses the 'autoconfig' field
            detect = 8      // uses proxy auto-discovering protocol
        }

        private Dictionary<string, Dictionary<string, string>> _regLocations = new Dictionary<string, Dictionary<string, string>>() {
            { "ProxySettingsPerUser", new Dictionary<String, String>() {
                { "Path", @"HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" },
                { "Name", "ProxySettingsPerUser" } }
            },
            { "CurrentUser", new Dictionary<String, String>() {
                { "Path", @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" },
                { "Name", "DefaultConnectionSettings"} }
            },
            { "LocalMachine", new Dictionary<String, String>() {
                { "Path", @"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" },
                { "Name", "WinHttpSettings"} }
            },
            { "LocalMachineWoW64", new Dictionary<String, String>() {
                { "Path", @"HKEY_LOCAL_MACHINE\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" },
                { "Name", "WinHttpSettings"} }
            }
        };

        public class WinHttpProxyConfig
        {
            public int Version { get; set; }
            public int Counter { get; set; }
            public int ConfigFlags { get; set; }
            public string Proxy { get; set; }
            public string Bypass { get; set; }
            public string AutoConfig { get; set; }
            public bool ProxySettingsPerUser { get; set; }
            public ContextObject Context { get; set; }

    }



        [SupportedOSPlatform("windows")]
        public List<WinHttpProxyConfig> GetWinHttpProxySettings(ContextObject[] contextObject)
        {
            List<WinHttpProxyConfig> whpcList = new List<WinHttpProxyConfig>();

            foreach (ContextObject ctx in contextObject) {
                idx = -4;
                byte[] rawConfig;
                bool ProxySettingsPerUser = false;

                try { 
                    var SettingsLocation = _regLocations["ProxySettingsPerUser"];
                    if (Registry.GetValue(SettingsLocation["Path"], SettingsLocation["Name"], null) == null)
                    {
                        ProxySettingsPerUser = true;
                    }

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Error ProxySettingsPerUser: " + ex);
                }

                try
                {
                    var SettingsLocation = _regLocations[ctx.ToString()];
                    rawConfig = (byte[]) Registry.GetValue(SettingsLocation["Path"], SettingsLocation["Name"], "");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Error SettingsLocation: " + ex);
                    rawConfig = Encoding.ASCII.GetBytes("18, 00, 00, 00, 00, 00, 00, 00, 01, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00");
                }

                WinHttpProxyConfig whpc = new WinHttpProxyConfig();

                whpc.Version = rawConfig[_idx(ref idx)];
                whpc.Counter = rawConfig[_idx(ref idx)];
                whpc.ConfigFlags = rawConfig[_idx(ref idx)] - 1; // we remove 1 because we don't want to display the "stuck bit"
                whpc.Proxy = _decodeString(_idx(ref idx), rawConfig);
                whpc.Bypass = _decodeString(_idx(ref idx), rawConfig);
                whpc.AutoConfig = _decodeString(_idx(ref idx), rawConfig);
                whpc.ProxySettingsPerUser = ProxySettingsPerUser;
                whpc.Context = ctx;

                whpcList.Add(whpc);

            }

            return whpcList;

        }

        [SupportedOSPlatform("windows")]
        public void GetWinHttpProxyView(ContextObject[] contextObject)
        {
            List<WinHttpProxyConfig> whpcList = GetWinHttpProxySettings(contextObject);

            foreach (WinHttpProxyConfig whpc in whpcList)
            {
                Console.WriteLine("Version: " + whpc.Version);
                Console.WriteLine("Counter: " + whpc.Counter);
                Console.WriteLine("ConfigFlags: " + whpc.ConfigFlags);
                Console.WriteLine("Proxy: " + whpc.Proxy);
                Console.WriteLine("Bypass: " + whpc.Bypass);
                Console.WriteLine("AutoConfig: " + whpc.AutoConfig);
                Console.WriteLine("ProxzSettingPerUser: " + whpc.ProxySettingsPerUser);
                Console.WriteLine("Context: " + whpc.Context);
            }

        }

        // INTERNAL: decodes a byte array
        private string _decodeString(int start, byte[] byteArray, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = Encoding.ASCII;
            }

            try
            {
                var strLen = byteArray[start];
                var str_ba = byteArray[(start + 4)..(start + 4 + strLen)];
                _idx(ref idx, strLen);
                return encoding.GetString(str_ba);
            } catch (IndexOutOfRangeException ex)
            {
                _idx(ref idx);
            }

            return "";
        }


        // INTERNAL: outputs current index value and increases it
        private int idx;
        private int _idx(ref int idx, int inc = 4)
        {  
            int ind = idx;
            return idx += inc;

        }


    }
}

推荐阅读