0

Here is my proxy code.

[Runtime.InteropServices.DllImport("wininet.dll", SetLastError = true)]
private static bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength);

public struct Struct_INTERNET_PROXY_INFO
{
    public int dwAccessType;
    public IntPtr proxy;
    public IntPtr proxyBypass;
}

private void UseProxy(string strProxy)
{
    const int INTERNET_OPTION_PROXY = 38;
    const int INTERNET_OPEN_TYPE_PROXY = 3;

    Struct_INTERNET_PROXY_INFO struct_IPI = default(Struct_INTERNET_PROXY_INFO);

    struct_IPI.dwAccessType = INTERNET_OPEN_TYPE_PROXY;
    struct_IPI.proxy = Marshal.StringToHGlobalAnsi(strProxy);
    struct_IPI.proxyBypass = Marshal.StringToHGlobalAnsi("local");

    IntPtr intptrStruct = Marshal.AllocCoTaskMem(Marshal.SizeOf(struct_IPI));

    Marshal.StructureToPtr(struct_IPI, intptrStruct, true);

    bool iReturn = InternetSetOption(IntPtr.Zero, INTERNET_OPTION_PROXY, intptrStruct, System.Runtime.InteropServices.Marshal.SizeOf(struct_IPI));
}

private void Button1_Click(System.Object sender, System.EventArgs e)
{
    Label4.Text = (TextBox1.Text + ":" + TextBox2.Text);

}

This code works fine with a windows from app. I tried using it in a console app and checked my ip but it did not work. Here is how i used it in a console app,

static void Main()
{
    Console.WriteLine("Ip before Proxy /r/n");
    HTTPGet req = new HTTPGet();
    req.Request("http://checkip.dyndns.org");
    string[] a = req.ResponseBody.Split(':');
    string a2 = a[1].Substring(1);
    string[] a3 = a2.Split('<');
    string a4 = a3[0];
    Console.WriteLine(a4);

    UseProxy("219.93.183.106:8080");
    Console.WriteLine("Ip after Proxy /r/n");
    HTTPGet req1 = new HTTPGet();
    req1.Request("http://checkip.dyndns.org");
    string[] a1 = req1.ResponseBody.Split(':');
    string a21 = a1[1].Substring(1);
    string[] a31 = a21.Split('<');
    string a41 = a31[0];
    Console.WriteLine(a41);
    Console.ReadLine();
}

HTTPGet is a class i got from : Get public/external IP address?

I want the proxy to work with the console app. I am not sure what is the problem I will also run multiple instances of program so I want each console using one proxy and it should only affect the browsing of the console and not whole computer. Proxies will have no authentication.

Here is my own HTTPBase class which handles all the http requests for the whole app,

namespace ConsoleApplication1
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Net;
    using System.Web;
    using System.Runtime.InteropServices;


    public class HTTPBase
    {
        private CookieContainer _cookies = new CookieContainer();
        private string _lasturl;
        private int _retries = 3;
        private string _useragent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.1)";

        public HTTPBase()
        {
            ServicePointManager.UseNagleAlgorithm = false;
            ServicePointManager.Expect100Continue = false;
        }

        public void ClearCookies()
        {
            this._cookies = new CookieContainer();
        }

        public static string encode(string str)
        {
            // return System.Net.WebUtility.HtmlEncode(str);
            return HttpUtility.UrlEncode(str);
            //return str;
        }

        public string get(string url)
        {
            for (int i = 0; i < this._retries; i++)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.UserAgent = this._useragent;
                    request.CookieContainer = this._cookies;
                    if (this._lasturl != null)
                    {
                        request.Referer = this._lasturl;
                    }
                    else
                    {
                        request.Referer = url;
                    }
                    this._lasturl = url;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch (Exception exception)
                {
                    if ((i + 1) == this._retries)
                    {
                        throw exception;
                    }
                }
            }
            throw new Exception("Failed");
        }

        public string post(string url, string postdata)
        {
            for (int i = 0; i < this._retries; i++)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ContentType = "application/x-www-form-urlencoded";
                    if (this._lasturl != null)
                    {
                        request.Referer = this._lasturl;
                    }
                    else
                    {
                        request.Referer = url;
                    }
                    this._lasturl = url;
                    request.Method = "POST";
                    request.UserAgent = this._useragent;
                    request.CookieContainer = this._cookies;
                    request.ContentLength = postdata.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(postdata);
                        }
                    }
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch (Exception exception)
                {
                    if (this._lasturl.Contains("youtuberender.php"))
                    {
                        return "bypassing youtube error";
                    }
                    if ((i + 1) == this._retries)
                    {
                        throw exception;
                    }
                }
            }
            throw new Exception("Failed");
        }

        public string post(string url, string postdata, string referer)
        {
            for (int i = 0; i < this._retries; i++)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Referer = referer;
                    this._lasturl = url;
                    request.Method = "POST";
                    request.UserAgent = this._useragent;
                    request.CookieContainer = this._cookies;
                    request.ContentLength = postdata.Length;
                    using (Stream stream = request.GetRequestStream())
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.Write(postdata);
                        }
                    }
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
                catch (Exception exception)
                {
                    if (this._lasturl.Contains("youtube.com"))
                    {
                        return "bypassing youtube error";
                    }
                    if ((i + 1) == this._retries)
                    {
                        throw exception;
                    }
                }
            }
            throw new Exception("Failed");
        }

        public string XmlHttpRequest(string urlString, string xmlContent)
        {
            string str = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            request = (HttpWebRequest)WebRequest.Create(urlString);
            try
            {
                byte[] bytes = Encoding.ASCII.GetBytes(xmlContent);
                request.Method = "POST";
                request.UserAgent = this._useragent;
                request.CookieContainer = this._cookies;
                request.ContentLength = bytes.Length;
                request.Headers.Add("X-Requested-With", "XMLHttpRequest");
                request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }
                response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (Stream stream2 = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream2))
                        {
                            str = reader.ReadToEnd();
                        }
                    }
                }
                response.Close();
            }
            catch (WebException exception)
            {
                throw new Exception(exception.Message);
            }
            catch (Exception exception2)
            {
                throw new Exception(exception2.Message);
            }
            finally
            {
                response.Close();
                response = null;
                request = null;
            }
            return str;
        }

        public string UserAgent
        {
            get
            {
                return this._useragent;
            }
            set
            {
                this._useragent = value;
            }
        }


    }
}

So I want to be able to add the proxy in this code. I will pass a variable from main form which will have the proxy:port format and I want this code to use the proxy. I am new to these proxy things and having some confusions. I use net framework 4.0 in VS 12.

Community
  • 1
  • 1
  • Just one question: why not using [WebRequest.DefaultWebProxy](http://msdn.microsoft.com/en-us/library/system.net.webrequest.defaultwebproxy.aspx) `WebRequest.DefaultWebProxy = new WebProxy("219.93.183.106", 8080);`? – Ulugbek Umirov Apr 07 '14 at 10:54

1 Answers1

0

You can use WebRequest.DefaultWebProxy

WebRequest.DefaultWebProxy = null;
using (WebClient wc = new WebClient())
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

WebRequest.DefaultWebProxy = new WebProxy("219.93.183.106", 8080);
using (WebClient wc = new WebClient())
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

Or you can set proxy explicitly:

using (WebClient wc = new WebClient { Proxy = null })
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}

using (WebClient wc = new WebClient { Proxy = new WebProxy("219.93.183.106", 8080) })
{
    string html = wc.DownloadString("http://checkip.dyndns.org");
    Console.WriteLine(XDocument.Parse(html).Root.Element("body").Value);
}
Ulugbek Umirov
  • 12,719
  • 3
  • 23
  • 31
  • Can you integrate this code with my HTTPBase. I am not sure how to do it. If you can pass me that code it would be really helpful – user3502927 Apr 07 '14 at 13:44
  • @user3502927 Just redeclare `UseProxy` as `private void UseProxy(string strProxy) { WebRequest.DefaultWebProxy = string.IsNullOrEmpty(strProxy) ? null : new WebProxy(strProxy); }`. – Ulugbek Umirov Apr 07 '14 at 15:11
  • i am not sure why but it does not works with my class httpBase code. I have tried adding the code into the httpbase.get string and also added the code in main form before requesting for ip but I don't get the proxy to work. – user3502927 Apr 08 '14 at 10:23
  • i found it ot but not sure what is the fix. It works on specific ip and doesn't work on sone proxies. My windows form app works on all ips i have but thei console juz works on some – user3502927 Apr 08 '14 at 12:04
  • This one doesn't works with this ip, 111.161.126.85:80 – user3502927 Apr 08 '14 at 12:14