You can use the following GetDefaultProxy method to retrieve the system proxy settings.
The following system proxy types (which can be set in Internet Options/Connections/Lan Settings/Advanced) are supported:
- Secure (https) ~ corresponds to HTTP CONNECT proxies - Rebex.Net.ProxyType.HttpConnect
- Socks (version 4) ~ corresponds SOCKS 4A proxies - Rebex.Net.ProxyType.Socks4a
The other two options which can be set using system settings (FTP-only and HTTP-only proxies) are not suitable for other protocols.
var sftp = new Sftp()
sftp.Proxy = ProxyHelper.GetDefaultProxy()
//sftp.LogWriter = new ConsoleLogWriter(LogLevel.Info)
sftp.Connect("test.rebex.net", 22)
sftp.Login("demo", "password")
...
public static Proxy GetDefaultProxy()
{
using (var registry = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"))
{
if ((int)registry.GetValue("ProxyEnable") == 1)
{
var proxyServer = (string)registry.GetValue("ProxyServer")
if (!string.IsNullOrEmpty(proxyServer))
{
var proxy = new Proxy()
foreach (string entry in proxyServer.Split(new char[] { ';' }))
{
int n
string hostAndPort
if ((n = entry.IndexOf('=')) == -1)
{
if (entry.StartsWith("http://", StringComparison.Ordinal))
hostAndPort = entry.Substring(7)
else
hostAndPort = entry
proxy.ProxyType = ProxyType.HttpConnect
}
else
{
hostAndPort = entry.Substring(n + 1)
string type = entry.Substring(0, n)
if (type == "socks")
proxy.ProxyType = ProxyType.Socks4a
else if (type == "https")
proxy.ProxyType = ProxyType.HttpConnect
else
continue
}
n = hostAndPort.IndexOf(':')
if (n < 1)
throw new ApplicationException("Invalid proxy format: " + hostAndPort)
proxy.Host = hostAndPort.Substring(0, n)
int port
if (!int.TryParse(hostAndPort.Substring(n + 1), out port))
{
throw new ApplicationException("Invalid proxy port: " + hostAndPort)
}
proxy.Port = port
}
if (proxy.ProxyType == ProxyType.None)
throw new ApplicationException("None of the default proxies is supported.")
var proxyOverride = (string)registry.GetValue("ProxyOverride")
if (proxyOverride != null)
{
var bypassList = new List<string>()
foreach (string host in proxyOverride.Split(';'))
{
if (host == "<local>")
proxy.BypassProxyOnLocal = true
else
bypassList.Add(host)
}
proxy.BypassList = bypassList.ToArray()
}
return proxy
}
}
}
return new Proxy()
}