Mac OSX - 如何使用Cocoa甚至纯C函数获取代理配置?

Mau*_*res 5 macos networking cocoa objective-c nsurlconnection

我注意到我的应用程序没有使用机器可用的代理设置(我使用Charles代理来测试代理配置).使用NSURLConnection进行调用的应用程序的一部分使用代理正确使用和发出请求,应用程序的另一部分(显然是在Mono上运行的MonoMac应用程序)没有.

它不断发出请求,好像没有配置代理.是否有一个函数或对象可以用来获取NSURLConnection正在使用的相同代理配置?

Mau*_*res 10

为您提供所有代理信息的函数是SCDynamicStoreCopyProxies(),它可以在下面的示例中调用(一旦完成,您还需要CFRelease所有这些对象,因为它们都来自CF而不是直接Cocoa对象):

#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>

int main(int argc, const char * argv[])
{

  @autoreleasepool {

    CFDictionaryRef proxies = SCDynamicStoreCopyProxies(NULL);

    CFIndex count = CFDictionaryGetCount(proxies);

    NSLog(@"Number of keys is %ld", count);

    NSDictionary * proxyConfiguration = (NSDictionary*) proxies;

    for ( id key in proxyConfiguration.keyEnumerator ) {
      NSLog(@"Pair is %@ -> %@", key, [proxyConfiguration valueForKey: key]);
    }

  }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出将是这样的:

2012-11-07 16:33:57.844 network-test[6501:403] Number of keys is 12
2012-11-07 16:33:57.847 network-test[6501:403] Pair is HTTPEnable -> 1
2012-11-07 16:33:57.848 network-test[6501:403] Pair is HTTPSProxy -> 127.0.0.1
2012-11-07 16:33:57.848 network-test[6501:403] Pair is ExceptionsList -> (
    "www.google.com"
)
2012-11-07 16:33:57.849 network-test[6501:403] Pair is HTTPSPort -> 8888
2012-11-07 16:33:57.850 network-test[6501:403] Pair is __SCOPED__ -> {
    en1 =     {
        ExceptionsList =         (
            "www.google.com"
        );
        FTPPassive = 1;
        HTTPEnable = 1;
        HTTPPort = 8888;
        HTTPProxy = "127.0.0.1";
        HTTPSEnable = 1;
        HTTPSPort = 8888;
        HTTPSProxy = "127.0.0.1";
        SOCKSEnable = 1;
        SOCKSPort = 8889;
        SOCKSProxy = "127.0.0.1";
    };
}
2012-11-07 16:33:57.850 network-test[6501:403] Pair is HTTPProxy -> 127.0.0.1
2012-11-07 16:33:57.851 network-test[6501:403] Pair is SOCKSPort -> 8889
2012-11-07 16:33:57.852 network-test[6501:403] Pair is SOCKSProxy -> 127.0.0.1
2012-11-07 16:33:57.852 network-test[6501:403] Pair is HTTPSEnable -> 1
2012-11-07 16:33:57.853 network-test[6501:403] Pair is SOCKSEnable -> 1
2012-11-07 16:33:57.853 network-test[6501:403] Pair is HTTPPort -> 8888
2012-11-07 16:33:57.854 network-test[6501:403] Pair is FTPPassive -> 1
Run Code Online (Sandbox Code Playgroud)