public static object GetOrPost(string sUrl, out string Errmsg, Dictionary <string, string> PostData = null, bool IsRetByte = false, int Timeout = 5 *1000, bool KeepAlive = true, string UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36", string ContentType = "application/x-www-form-urlencoded; charset=UTF-8", int Retry = 0, CookieContainer Cookie = null, string Header = null, string ElseMethod = null, string PostJson = null, bool IsErrResponse = false, ProxyInfo Proxy = null, bool AllowAutoRedirect = true, string Referer = null, string Host = null) { try { var Res = GetOrPostAsync(sUrl, PostData, IsRetByte, Timeout, KeepAlive, UserAgent, ContentType, Retry, Cookie, Header, ElseMethod, PostJson, EnableAsync: false, Proxy: Proxy, Referer: Referer, AllowAutoRedirect: AllowAutoRedirect, Host: Host); Errmsg = Res.Result.Errmsg; if (IsErrResponse) { Errmsg = Res.Result.Errresponse; } return(Res.Result.oData); } catch { Errmsg = "Err!"; return(null); } }
private void AddToBlackList_Click(object sender, RoutedEventArgs e) { ProxyInfo proxy = (ProxyInfo)((Button)sender).Tag; foreach (IProxyClient client in Context.Get <IProxyClientSearcher>().SelectedClients.Where(item => item.Proxy == proxy)) { client.Proxy = null; } Context.Get <IBlackListManager>().Add(proxy); PageData.Remove(proxy); if (Paging.Page < Paging.PageCount) { int index = Paging.Page.Value * Context.Get <AllSettings>().PageSize; PageData.Add(FilteredData[index]); } if (PageData.Count == 0 && Paging.Page > 1) { Paging.Page--; } Data.Remove(proxy); FilteredData.Remove(proxy); Context.Get <IRatingManager>().UpdateRatingDataAsync(proxy, 1); UpdateStatusString(); }
/// <summary> /// Добавление прокси /// </summary> /// <param name="proxyInfo"></param> public void AddProxy(ProxyInfo proxyInfo) { try { if (_locker.TryEnterWriteLock(LOCK_TIMEOUT)) { Add(proxyInfo); } } catch (Exception e) { Console.WriteLine(e); } finally { if (_locker.IsWriteLockHeld) { _locker.ExitWriteLock(); } } if (_proxies.Count % 10 == 0) { SaveProxies(); } }
/// <summary> /// Opens the IRC session and attempts to connect to a server. /// </summary> /// <param name="server">The hostname or IP representation of a server.</param> /// <param name="port">The IRC port.</param> /// <param name="isSecure">True to use an encrypted (SSL) connection, false to use plain text.</param> /// <param name="nickname">The desired nickname.</param> /// <param name="userName">The username that will be shown to other users.</param> /// <param name="fullname">The full name that will be shown to other users.</param> /// <param name="autoReconnect">Indicates whether to automatically reconnect upon disconnection.</param> /// <param name="password">The optional password to supply while logging in.</param> /// <param name="invisible">Determines whether the +i flag will be set by default.</param> /// <param name="findExternalAddress"> /// Determines whether to find the external IP address by querying the IRC server upon /// connect. /// </param> public void Open(string server, int port, bool isSecure, string nickname, string userName, string fullname, bool autoReconnect, string password = null, bool invisible = false, bool findExternalAddress = true, ProxyInfo proxy = null) { if (string.IsNullOrEmpty(nickname)) { throw new ArgumentNullException("nickname"); } _password = password; _isInvisible = invisible; _findExternalAddress = findExternalAddress; Nickname = nickname; Server = server; Port = port; IsSecure = isSecure; Username = userName; FullName = fullname; NetworkName = Server; UserModes = new char[0]; AutoReconnect = autoReconnect; Proxy = proxy; _conn.Open(server, port, isSecure, Proxy); State = IrcSessionState.Connecting; }
/// <summary> /// Connects to the IRC session and attempts to connect to a server. When the task completes, it means the Socket has been setup, but registration has not necessailry been finished /// </summary> /// <param name="hostname">The hostname or IP representation of a server.</param> /// <param name="port">The IRC port.</param> /// <param name="isSecure">True to use an encrypted (SSL) connection, false to use plain text.</param> /// <param name="nickname">The desired nickname.</param> /// <param name="userName">The username that will be shown to other users.</param> /// <param name="fullname">The full name that will be shown to other users.</param> /// <param name="autoReconnect">Indicates whether to automatically reconnect upon disconnection.</param> /// <param name="password">The optional password to supply while logging in.</param> /// <param name="invisible">Determines whether the +i flag will be set by default.</param> /// <param name="findExternalAddress">Determines whether to find the external IP address by querying the IRC server upon connect.</param> /// <param name="proxy">Socks Proxy Info</param> public async Task ConnectAsync(string hostname, int port, bool isSecure, string nickname, string userName, string fullname, bool autoReconnect, string password = null, bool invisible = false, bool findExternalAddress = true, ProxyInfo proxy = null) { if (string.IsNullOrEmpty(nickname)) { throw new ArgumentNullException(nameof(nickname)); } _password = password; _isInvisible = invisible; _findExternalAddress = findExternalAddress; Nickname = nickname; Hostname = hostname; Port = port; IsSecure = isSecure; Username = userName; FullName = fullname; NetworkName = Hostname; // just for now UserModes = new char[0]; AutoReconnect = autoReconnect; Proxy = proxy; ForceDisconnect = false; await OpenSocketAsync().ConfigureAwait(false); }
public static ProxyInfo[] GetAll() { var proxyInfos = new Collection <ProxyInfo>(); foreach (var fileName in Directory.GetFiles("Proxy")) { var lines = File.ReadAllLines(fileName); if (lines != null && lines.Count() > 0) { foreach (var line in lines) { var arr = line.Split(':'); var proxyInfo = new ProxyInfo { Host = arr[0], Port = arr[1], UserName = arr[2], Pass = arr[3], }; if (CanPing(proxyInfo.Host)) { proxyInfos.Add(proxyInfo); } } } } return(proxyInfos.ToArray()); }
public void Open(string server, int port, bool isSecure, ProxyInfo proxy = null) { if (string.IsNullOrEmpty(server)) { throw new ArgumentNullException(nameof(server)); } if (port <= 0 || port > 65535) { throw new ArgumentOutOfRangeException(nameof(port)); } if (_closeCts != null) { Close(); } _server = server; _port = port; _isSecure = isSecure; _proxy = proxy; _writeQueue = new BlockingCollection <IrcMessage>(); _closeCts = new CancellationTokenSource(); SocketMain(_closeCts.Token); }
public void OnAliveProxy(ProxyInfo proxyInfo) { if (ProxyAlive != null) { ProxyAlive(proxyInfo); } }
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { if (!Conf.IsUrl(Url)) { TextBox_EndPointURL.BorderBrush = new SolidColorBrush(Colors.Red); args.Cancel = true; } if (UseProxy) { if (string.IsNullOrEmpty(ProxyPanel.Host) || string.IsNullOrWhiteSpace(ProxyPanel.Host)) { ProxyPanel.TextBox_ProxyHost.BorderBrush = new SolidColorBrush(Colors.Red); args.Cancel = true; return; } if (ProxyPanel.Port == 0) { args.Cancel = true; return; } ProxyInfo = new ProxyInfo(ProxyPanel.Host, ProxyPanel.Port, ProxyPanel.ProxyType) { User = ProxyPanel.Credential?.User ?? "", Password = ProxyPanel.Credential?.Password ?? "" }; } else { ProxyInfo = new ProxyInfo(); } }
private void DlgAddAccount_Load(object sender, EventArgs e) { try { SetControls(false); if (_oldemail != null && _oldemail != string.Empty) { this.Icon = IconCtrl.GetIconFromResx(TreeConstants.ICON_KEYS); txtEmail.Text = _account.Email; txtPassword.Text = _account.Password; txtUserName.Text = _account.UserName; txtUserId.Text = _account.UserId; txtGender.Text = _account.Gender ? "ÄÐ" : "Å®"; this.Text = "±à¼Õ˺Å"; } else { _account = new AccountInfo(); this.Text = "Ìí¼ÓÕ˺Å"; } _hh = new HttpHelper(); ProxyInfo proxy = ConfigCtrl.GetProxy(); if (proxy != null && proxy.Enable == true) { _hh.SetProxy(proxy.Server, proxy.Port, proxy.UserName, proxy.Password); } } catch (Exception ex) { ErrorHandler.ShowMessageBox(TreeConstants.EXCEPTION_MODULE, ex); } }
private void UpdateValidateProgressBarProxyManager(object sender, ProgressChangedEventArgs args) { this.progressBarProxyManager.Value = args.ProgressPercentage; ProxyInfo pi = args.UserState as ProxyInfo; lock (proxiesTable) { if (pi != null && pi.RTT < 0) { DataRow dr; if (proxiesRows.TryGetValue(pi.ProxyAddress, out dr)) { proxiesTable.Rows.Remove(dr); proxiesRows.Remove(pi.ProxyAddress); } } else if (pi != null) { DataRow dr; if (proxiesRows.TryGetValue(pi.ProxyAddress, out dr)) { if (dr != null) { dr["Latency"] = new LatencyColumnValue(pi.RTT); } } } } if (dgProxyList.Rows.Count > 0) { dgProxyList.FirstDisplayedScrollingRowIndex = 0; } }
private void UpdateProxyUsingInfo(object sender, ProxyUsingChangedEvnetHandlerArgs args) { ProxyInfo pi = ins.SelectiveProxyGuide.CurrentProxyInfo; if (pi != null) { this.lblProxyAddress.Text = pi.ProxyAddress; this.lblProxyLatency.Text = "(" + pi.RTT + " ms)"; this.lblProxySource.Text = pi.Location; double per = (double)pi.RTT / 2000; if (per > 1) { per = 1; } Color c = Color.FromArgb((int)(0xff * per), (int)(0xff * (1.0 - per)), 0); this.lblProxyColor.BackColor = c; this.lblProxyStatusWorkingProxy.Text = pi.ProxyAddress; Log("Using Proxy: " + this.lblProxyAddress.Text); } else { this.lblProxyAddress.Text = "No Proxy Working"; this.lblProxyStatusWorkingProxy.Text = "No Proxy Working"; this.lblProxyLatency.Text = ""; this.lblProxySource.Text = ""; this.lblProxyColor.BackColor = Color.Red; Log(this.lblProxyAddress.Text); } }
public List <ProxyInfo> Load() { List <ProxyInfo> result = new List <ProxyInfo>(); if (!File.Exists(_fileName)) { return(result); } string data = File.ReadAllText(_fileName); string[] split = new[] { "\r\n" }; string[] list = data.Split(split, StringSplitOptions.RemoveEmptyEntries); foreach (string s in list) { try { var proxy = new ProxyInfo(); if (proxy.Load(s)) { result.Add(proxy); } } catch (Exception) { } } return(result); }
async Task Exec(ProxyInfo info) { using var scope = _serviceProvider.CreateScope(); var proxyService = scope.ServiceProvider.GetService <IProxyService>(); if (string.IsNullOrWhiteSpace(info.IP)) { return; } var exists = await proxyService.ExistsAsync(info.IP, info.Port); if (exists) { return; } await proxyService.AddAsync(new Service.Models.ProxyDto { AnonymousDegree = (int)info.AnonymousDegree, CreatedTime = DateTime.Now, IP = info.IP, Port = info.Port, Score = 1, UpdatedTime = DateTime.Now }); _logger.LogInformation($"successfully added {info.IP}:{info.Port}"); }
public string ProxyUrl(MBTrailers.ITunesTrailer trailer) { Uri uri = new Uri(trailer.RealPath); ProxyInfo proxyInfo = new ProxyInfo(uri.Host, uri.PathAndQuery, ProxyInfo.ITunesUserAgent, uri.Port); TrailerInfo trailerInfo = new TrailerInfo(TrailerType.Remote, proxyInfo.LocalFilename, trailer.ParentalRating, trailer.Genres); using (ChannelFactory <ITrailerProxy> factory = new ChannelFactory <ITrailerProxy>(new NetNamedPipeBinding(), "net.pipe://localhost/mbtrailers")) { ITrailerProxy proxyServer = factory.CreateChannel(); try { proxyServer.SetProxyInfo(proxyInfo); proxyServer.SetTrailerInfo(trailerInfo); } catch (Exception e) { Logger.ReportException("Error setting proxy info", e); Logger.ReportError("Inner Exception: " + e.InnerException.Message); } finally { (proxyServer as ICommunicationObject).Close(); } } var target = Path.Combine(cacheDir, proxyInfo.LocalFilename); return(File.Exists(target) ? target : string.Format("http://localhost:{0}/{1}", this.port, proxyInfo.LocalFilename)); }
public void SetProxySettings(ProxyInfo proxyInfo) { CheckDisposed(); if (proxyInfo == null) { throw new ArgumentNullException(nameof(proxyInfo)); } CheckConnected(); XElement request = new XElement("set_proxy_settings", proxyInfo.UseHttpProxy ? new XElement("use_http_proxy") : null, proxyInfo.UseSocksProxy ? new XElement("use_socks_proxy") : null, proxyInfo.UseHttpAuthentication ? new XElement("use_http_auth") : null, new XElement("proxy_info", new XElement("http_server_name", proxyInfo.HttpServerName), new XElement("http_server_port", proxyInfo.HttpServerPort), new XElement("http_user_name", proxyInfo.HttpUserName), new XElement("http_user_passwd", proxyInfo.HttpUserPassword), new XElement("socks_server_name", proxyInfo.SocksServerName), new XElement("socks_server_port", proxyInfo.SocksServerPort), new XElement("socks_version", proxyInfo.SocksVersion), new XElement("socks5_user_name", proxyInfo.Socks5UserName), new XElement("socks5_user_passwd", proxyInfo.Socks5UserPassword), new XElement("no_proxy", proxyInfo.NoProxyHosts))); CheckResponse(PerformRpc(request)); }
public async void MeasureAsync(ProxyInfo proxyInfo) { BandwidthState previousState = proxyInfo.BandwidthData.State; proxyInfo.BandwidthData.Progress = 0; proxyInfo.BandwidthData.State = BandwidthState.Progress; proxyInfo.BandwidthData.CancellationToken = new CancellationTokenSource(); try { BanwidthInfo result = await GetBandwidthInfo(proxyInfo, proxyInfo.BandwidthData.CancellationToken); if (result != null) { UpdateBandwidthData(proxyInfo, result); } else { proxyInfo.BandwidthData.State = BandwidthState.Error; } } catch (TaskCanceledException) { proxyInfo.BandwidthData.State = previousState; } catch (Exception) { proxyInfo.BandwidthData.State = BandwidthState.Error; } }
/// <summary> /// 下载文件 /// </summary> /// <param name="sUrl"></param> /// <param name="sPath"></param> /// <param name="Retry"></param> /// <returns></returns> public static bool GetFile(string sUrl, string sPath, out string Errmsg, int Timeout = 10 *1000, bool KeepAlive = true, string UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36", string ContentType = "application/x-www-form-urlencoded; charset=UTF-8", int Retry = 0, CookieContainer Cookie = null, ProxyInfo Proxy = null) { object oValue = GetOrPost(sUrl, out Errmsg, null, false, Timeout, KeepAlive, UserAgent, ContentType, Retry, Cookie, null, Proxy: Proxy); if (oValue == null) { return(false); } try { Directory.CreateDirectory(Path.GetDirectoryName(sPath)); File.WriteAllText(sPath, oValue.ToString()); return(true); } catch (Exception e) { Errmsg = e.Message; return(false); } }
public void OnAliveProxy(ProxyInfo proxyInfo) { if (proxyInfo.Details != null && proxyInfo.Details.Details != null && Context.Get <AllSettings>().IgnoredHttpProxyTypes.Any(item => item.ToString() == proxyInfo.Details.Details.Type)) { return; } if (ExportAllowed && ExportSettings.ExportSearchResult) { lock (this) { if (stream == null) { stream = CreateFile(GetDirectory(proxyInfo.Details.Details)); } stream.WriteLine(proxyInfo.ToString(ExportSettings.ExportCountry, ExportSettings.ExportProxyType)); } } Context.Get <ISearchResult>().Add(proxyInfo); isProxyFound = true; if (!isTimingNotificationSent) { isTimingNotificationSent = true; Context.Get <IGA>().EndTrackTiming(TimingCategory.SearchSpeed, TimingVariable.TimeForGetFirstProxy, GAResources.FirstProxyFound); } }
protected override void SetProxy(ProxyInfo proxyInfo) { if (proxyInfo != null) { SocksProxyTypes type = proxyInfo.Details.Details.GetStrongType <SocksProxyTypes>(); if (type == SocksProxyTypes.Socks5) { Context.Get <IMessageBox>().Information(Resources.ThisClientDoesntSupportSocks5Proxies); IsProxyChangeCancelled = true; return; } if (type != SocksProxyTypes.Socks4) { if (Context.Get <IMessageBox>().YesNoQuestion(Resources.TypeOfProxyIsNotDefinedDoYouWantToContinue) == MessageBoxResult.No) { IsProxyChangeCancelled = true; return; } } } base.SetProxy(proxyInfo); }
public FtpUpdater(Uri serverUri, int discoveryPriority, int downloadPriority = 1, NetworkCredential credentials = null) : base(serverUri.Host, discoveryPriority, downloadPriority) { if (serverUri == null) { throw new ArgumentNullException(nameof(serverUri)); } if (credentials == null) { var info = serverUri.UserInfo.Split(new[] { ':' }, 2, StringSplitOptions.None); if (info.Length == 2) { credentials = new NetworkCredential(info[0], info[1]); } } ProxyInfo p = new ProxyInfo { Host = "127.0.0.1", Port = 1083 }; _client = new FtpClientHttp11Proxy(p); _client.Host = serverUri.Host; _client.Credentials = credentials; if (!serverUri.IsDefaultPort) { _client.Port = serverUri.Port; } _client.EncryptionMode = FtpEncryptionMode.Explicit; _client.DataConnectionEncryption = true; // Retrying is handled higher up the tree _client.RetryAttempts = 1; }
public static object GetValue(object dat, string property, ref bool propIsfound) { if (dat == null) { propIsfound = false; return(null); } else { propIsfound = true; Type datType = dat.GetType(); varInfo var = GetVar(datType, property.ToUpper()); if (var == null) { propIsfound = false; return(ProxyInfo.GetPropValue(dat, property, ref propIsfound)); } try { Result result = doEval(dat, var.Item); if (result.HasError) { return(result.Error); } else { return(result.Value); } } catch { return(var.err); } } }
private bool GetRequest(ProxyInfo proxy) { try { using (HttpRequest client = GenerateHttpClientWithProxySettings(proxy)) { client.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); client.AddHeader("UserAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"); client.AddHeader("Accept-Language", "en-US;q=0.7,en;q=0.3"); //client["Accept-Encoding"]= "gzip, deflate, br"; client.EnableEncodingContent = true; client.AddHeader("Referer", URL_CHECK); client.SslCertificateValidatorCallback = (sender, certificate, chain, errors) => { return(true); }; var message = client.Get(URL_CHECK); return(message.IsOK); } } catch (Exception e) { Log.Error($"error request via proxy: {proxy}, {e}"); } return(false); }
public void Cancel(ProxyInfo proxyInfo) { if (proxyInfo.BandwidthData.CancellationToken != null) { proxyInfo.BandwidthData.CancellationToken.Cancel(); } proxyInfo.BandwidthData.CancellationToken = null; }
public void CountFailedRequest(ProxyInfo proxy) { EnsureProxiesHaveBeenRead(); var statistics = Find(proxy).IncrementFailedCount(); RemoveIfNeeded(statistics); }
private object CreateProxy(ProxyInfo info, ProxyMode mode) { var proxy = (Proxy)Activator.CreateInstance(info.ImplementationType); proxy.Provider = this; proxy.Mode = mode; return(proxy); }
public void ChangeProxy(ProxyChangePolicy policy) { rwl.EnterWriteLock(); ProxyInfo newProxy = proxyManager.DequeueFastestProxy(true); ChangeProxy(newProxy, policy); rwl.ExitWriteLock(); }
public ApiEndPoint(string address) { Address = address; UseHttpAuth = false; Credential = new HttpBasicAuthCredential(); UseProxy = false; Proxy = new ProxyInfo(); }
internal static IEnumerable <Uri> getProxiesForUrl( Uri requestUrl, string userAgent) { IntPtr hHttpSession = IntPtr.Zero; string[] proxyList = null; ; try { hHttpSession = WinHttpOpen(userAgent, AccessType.NoProxy, null, null, 0); if (hHttpSession != IntPtr.Zero) { AutoProxyOptions autoProxyOptions = new AutoProxyOptions(); autoProxyOptions.Flags = AccessType.AutoDetect; autoProxyOptions.AutoLogonIfChallenged = true; autoProxyOptions.AutoDetectFlags = AutoDetectType.Dhcp | AutoDetectType.DnsA; ProxyInfo proxyInfo = new ProxyInfo(); if (WinHttpGetProxyForUrl(hHttpSession, requestUrl.ToString(), ref autoProxyOptions, ref proxyInfo)) { if (!string.IsNullOrEmpty(proxyInfo.Proxy)) { proxyList = proxyInfo.Proxy.Split(';', ' '); } } } } catch (System.DllNotFoundException) { // winhttp.dll is not found. } catch (System.EntryPointNotFoundException) { // A method within winhttp.dll is not found. } finally { if (hHttpSession != IntPtr.Zero) { WinHttpCloseHandle(hHttpSession); hHttpSession = IntPtr.Zero; } } if (proxyList != null && proxyList.Length > 0) { Uri proxyUrl; foreach (string address in proxyList) { if (tryCreateUrlFromPartialAddress(address, out proxyUrl)) { yield return(proxyUrl); } } } }
public void ChangeProxy(ProxyInfo newProxy, ProxyChangePolicy policy) { rwl.EnterWriteLock(); errorTimes = 0; var args = new ProxyUsingChangedEvnetHandlerArgs(); args.OldProxy = currentProxyInfo; if (currentProxyInfo != null) { switch (policy) { case ProxyChangePolicy.TO_PENDING: proxyManager.EnqueuePendingProxy(currentProxyInfo); break; case ProxyChangePolicy.TO_GOOD: proxyManager.EnqueueGoodProxy(currentProxyInfo); break; case ProxyChangePolicy.DELETE: proxyManager.DeleteProxy(currentProxyInfo); break; default: throw new ArgumentOutOfRangeException("policy"); } } currentProxyInfo = newProxy; args.NewProxy = currentProxyInfo; if (currentProxyInfo != null) { IPAddress ip; if (IPAddress.TryParse(currentProxyInfo.HttpProxy.Address.Host, out ip)) { currentProxyIPAddress = new IPAddress[1] { ip }; } else { //host name is not an ip address currentProxyIPAddress = dnsCache.GetIPAddress(currentProxyInfo.HttpProxy.Address.Host); } currentProxyPort = currentProxyInfo.HttpProxy.Address.Port; } else { currentProxyIPAddress = null; currentProxyPort = 80; } if (OnProxyUsingChanged != null) { OnProxyUsingChanged(this, args); } rwl.ExitWriteLock(); }
internal static IEnumerable<Uri> GetProxiesForUrl( Uri requestUrl, string userAgent) { IntPtr hHttpSession = IntPtr.Zero; string[] proxyList = null; ; try { hHttpSession = WinHttpOpen(userAgent, AccessType.NoProxy, null, null, 0); if (hHttpSession != IntPtr.Zero) { AutoProxyOptions autoProxyOptions = new AutoProxyOptions(); autoProxyOptions.Flags = AccessType.AutoDetect; autoProxyOptions.AutoLogonIfChallenged = true; autoProxyOptions.AutoDetectFlags = AutoDetectType.Dhcp | AutoDetectType.DnsA; ProxyInfo proxyInfo = new ProxyInfo(); if (WinHttpGetProxyForUrl(hHttpSession, requestUrl.ToString(), ref autoProxyOptions, ref proxyInfo)) { if (!string.IsNullOrEmpty(proxyInfo.Proxy)) { proxyList = proxyInfo.Proxy.Split(';', ' '); } } } } catch (System.DllNotFoundException) { // winhttp.dll is not found. } catch (System.EntryPointNotFoundException) { // A method within winhttp.dll is not found. } finally { if (hHttpSession != IntPtr.Zero) { WinHttpCloseHandle(hHttpSession); hHttpSession = IntPtr.Zero; } } if (proxyList != null && proxyList.Length > 0) { Uri proxyUrl; foreach (string address in proxyList) { if (TryCreateUrlFromPartialAddress(address, out proxyUrl)) { yield return proxyUrl; } } } }
public Uploader() { Errors = new List<string>(); IsUploading = false; BufferSize = 8192; AllowReportProgress = true; ServicePointManager.DefaultConnectionLimit = 25; ServicePointManager.Expect100Continue = false; ServicePointManager.UseNagleAlgorithm = false; if (ProxyInfo == null) { ProxyInfo = new ProxyInfo(); } }
internal static bool GetProxyDetails(out ProxyInfo proxyInfo) { NativeStructs.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig = new NativeStructs.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG(); bool result = SafeNativeMethods.WinHttpGetIEProxyConfigForCurrentUser(ref proxyConfig); bool autoDetect; string autoConfigUrl; string proxy; string proxyBypass; if (result) { autoDetect = proxyConfig.fAutoDetect; autoConfigUrl = Marshal.PtrToStringUni(proxyConfig.lpszAutoConfigUrl); proxy = Marshal.PtrToStringUni(proxyConfig.lpszProxy); proxyBypass = Marshal.PtrToStringUni(proxyConfig.lpszProxyBypass); if (proxyConfig.lpszAutoConfigUrl != IntPtr.Zero) { SafeNativeMethods.GlobalFree(proxyConfig.lpszAutoConfigUrl); proxyConfig.lpszAutoConfigUrl = IntPtr.Zero; } if (proxyConfig.lpszProxy != IntPtr.Zero) { SafeNativeMethods.GlobalFree(proxyConfig.lpszProxy); proxyConfig.lpszProxy = IntPtr.Zero; } if (proxyConfig.lpszProxyBypass != IntPtr.Zero) { SafeNativeMethods.GlobalFree(proxyConfig.lpszProxyBypass); proxyConfig.lpszProxyBypass = IntPtr.Zero; } } else { autoDetect = false; autoConfigUrl = null; proxy = null; proxyBypass = null; } proxyInfo = new ProxyInfo(autoDetect, autoConfigUrl, proxy, proxyBypass); return result; }
public static void TestProxyAccount(ProxyInfo acc) { string msg = "Success!"; try { NetworkCredential cred = new NetworkCredential(acc.UserName, acc.Password); WebProxy wp = new WebProxy(acc.GetAddress(), true, null, cred); WebClient wc = new WebClient { Proxy = wp }; wc.DownloadString("http://www.google.com"); } catch (Exception ex) { msg = ex.Message; } if (!string.IsNullOrEmpty(msg)) { MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public ProxyUI() { InitializeComponent(); WebProxy proxy = ZAppHelper.GetDefaultWebProxy(); Proxy = new ProxyInfo(Environment.UserName, "", proxy.Address.Host, proxy.Address.Port); }
/// <summary> /// 代理ip测试方法 /// </summary> /// <param name="url">测试网页链接</param> /// <param name="info">代理ip信息</param> /// <returns>4次访问的均毫秒,最大为20000</returns> public static int GetHtmlByProxy(string url,ProxyInfo info) { const int testCount = 4; string str = ""; if (string.IsNullOrEmpty(url)) return 20000; int count = 0, succ = 0; if (!url.StartsWith("http://")) url = "http://" + url; int mini = 0;//请求时间(毫秒) while (count < testCount) { count++; DateTime dt = DateTime.Now; HttpWebRequest req = null; HttpWebResponse rep = null; try { req = (HttpWebRequest)WebRequest.Create(url); req.Timeout = 3000; req.Proxy = new WebProxy(info.Ip, info.Port); req.ServicePoint.ConnectionLimit = 30; req.ContentType = "text/html"; req.Headers.Add("Accept-language", "zh-cn,zh;q=0.5"); req.Headers.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7"); req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4"; req.Headers.Add("Accept-Encoding", "gzip, deflate"); req.Headers.Add("Keep-Alive", "300"); rep = (HttpWebResponse)req.GetResponse(); Stream resStream = (rep.ContentEncoding == "gzip" ? new GZipStream(rep.GetResponseStream(), CompressionMode.Decompress) : rep.GetResponseStream()); if (resStream != null) { var sr = new StreamReader(resStream, Encoding.Default); string item = sr.ReadToEnd(); if (!string.IsNullOrEmpty(item) && item.IndexOf("360buy.com") > 0) { succ++; mini += (int) (DateTime.Now - dt).TotalMilliseconds; } else { mini += 5000; } } else { mini += 5000; } } catch { mini += 5000; } finally { if (req != null) req.Abort(); if (rep != null) { rep.Close(); } } } if (succ == 0) { return 20000; } //var bl = testCount * 50 / str.Length;//链接比重 成功次数越少,值越大。 return (int) Math.Ceiling((double) (mini*count)/(testCount*succ)); }
void IHostingPeer.SubscribeProxy(ProxyInfo info) { Channel.SubscribeProxy(info); }
public void ProxyAdd(ProxyInfo acc) { Config.ProxyList.Add(acc); ucProxyAccounts.AccountsList.Items.Add(acc); ucProxyAccounts.AccountsList.SelectedIndex = ucProxyAccounts.AccountsList.Items.Count - 1; }
static ProxyInfo GetSingleProxy(string connection) { var list = new InternetPerConnOptionList(); var options = new InternetConnectionOption[]{ new InternetConnectionOption(){ m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS }, new InternetConnectionOption(){ m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER } }; // default stuff list.dwSize = Marshal.SizeOf(list); if (!string.IsNullOrEmpty(connection)) list.pszConnection = Marshal.StringToHGlobalAuto(connection); list.dwOptionCount = options.Length; list.dwOptionError = 0; var optSize = Marshal.SizeOf(typeof(InternetConnectionOption)); var optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length); // copy the array over into that spot in memory ... for (var i = 0; i < options.Length; i++) { var opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize)); Marshal.StructureToPtr(options[i], opt, false); } list.pOptions = optionsPtr; // and then make a pointer out of the whole list var ipcoListPtr = Marshal.AllocCoTaskMem(list.dwSize); Marshal.StructureToPtr(list, ipcoListPtr, false); // and finally, call the API method! var success = NativeMethods.InternetQueryOption(IntPtr.Zero, (int)InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION, ipcoListPtr, ref list.dwSize); Marshal.PtrToStructure(ipcoListPtr, list); Marshal.PtrToStructure(list.pOptions, options[0]); Marshal.PtrToStructure(new IntPtr(list.pOptions.ToInt32() + optSize), options[1]); var proxyInfo = new ProxyInfo() { ConnectionName = connection, Flags = options[0].m_Value.m_Int, Proxy = Marshal.PtrToStringAuto(options[1].m_Value.m_StringPtr) }; // FREE the data ASAP Marshal.FreeCoTaskMem(optionsPtr); Marshal.FreeCoTaskMem(ipcoListPtr); return proxyInfo; }