C# Connecting Through Proxy

C# Connecting Through Proxy

This is easily achieved either programmatically, in your code, or declaratively in either the web.config or the app.config.

You can programmatically create a proxy like so:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[ultimate destination of your request]");
WebProxy myproxy = new WebProxy("[your proxy address]", [your proxy port number]);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

You're basically assigning the WebProxy object to the request object's proxy property. This request will then use the proxy you define.

To achieve the same thing declaratively, you can do the following:

<system.net>
<defaultProxy>
<proxy
proxyaddress="http://[your proxy address and port number]"
bypassonlocal="false"
/>
</defaultProxy>
</system.net>

within your web.config or app.config. This sets a default proxy that all http requests will use. Depending upon exactly what you need to achieve, you may or may not require some of the additional attributes of the defaultProxy / proxy element, so please refer to the documentation for those.

How to use Proxy with TcpClient.ConnectAsync()?

I find a solution base on .NET: Connecting a TcpClient through an HTTP proxy with authentication and Bypass the proxy using TcpClient

TcpClient _client;
NetworkStream _stream;

public TcpClient ProxyTcpClient(string targetHost, int targetPort, string httpProxyHost, int httpProxyPort, string proxyUserName, string proxyPassword)
{
const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Instance;
Uri proxyUri = new UriBuilder
{
Scheme = Uri.UriSchemeHttp,
Host = httpProxyHost,
Port = httpProxyPort
}.Uri;
Uri targetUri = new UriBuilder
{
Scheme = Uri.UriSchemeHttp,
Host = targetHost,
Port = targetPort
}.Uri;

WebProxy webProxy = new WebProxy(proxyUri, true);
webProxy.Credentials = new NetworkCredential(proxyUserName, proxyPassword);
WebRequest request = WebRequest.Create(targetUri);
request.Proxy = webProxy;
request.Method = "CONNECT";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Type responseType = responseStream.GetType();
PropertyInfo connectionProperty = responseType.GetProperty("Connection", Flags);
var connection = connectionProperty.GetValue(responseStream, null);
Type connectionType = connection.GetType();
PropertyInfo networkStreamProperty = connectionType.GetProperty("NetworkStream", Flags);
NetworkStream networkStream = (NetworkStream)networkStreamProperty.GetValue(connection, null);
Type nsType = networkStream.GetType();
PropertyInfo socketProperty = nsType.GetProperty("Socket", Flags);
Socket socket = (Socket)socketProperty.GetValue(networkStream, null);

return new TcpClient { Client = socket };
}

public static async Task<bool> ConnectAsync(string hostname, int port)
{
_client = ProxyTcpClient("IPTargetHost", 1234, "IPProxyHost", 5678, "Userproxy", "Userppwd");
_stream = conn._client.GetStream();

..... Do some stuff

// Connexion OK
return true;
}

C# Socket: connect to server through proxy server

See my answer here, maybe it will be helpful. The general idea is to first establish connection to a proxy, and then use HTTP CONNECT command to open another TCP connection to a given host and port.

C# TcpClient.Connect via a proxy

I don't really think .Net comes equipped with Socks5 support, or proxied TCP.

There are a couple of third-party implementations (google knows more), of course, but it's also pretty easy to implement (part of) RFC 1928 yourself.

Here is an example Socks5 client I just hacked together. You will really want to clean it up :p. Just does the auth negotiation, connection setup and finally a simple http request.

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tcpsocks5
{
static class Program
{
static void ReadAll(this NetworkStream stream, byte[] buffer, int offset, int size)
{
while (size != 0) {
var read = stream.Read(buffer, offset, size);
if (read < 0) {
throw new IOException("Premature end");
}
size -= read;
offset += read;
}
}
static void Main(string[] args)
{
using (var client = new TcpClient()) {
client.Connect(ip, port); // Provide IP, Port yourself
using (var stream = client.GetStream()) {
// Auth
var buf = new byte[300];
buf[0] = 0x05; // Version
buf[1] = 0x01; // NMETHODS
buf[2] = 0x00; // No auth-method
stream.Write(buf, 0, 3);

stream.ReadAll(buf, 0, 2);
if (buf[0] != 0x05) {
throw new IOException("Invalid Socks Version");
}
if (buf[1] == 0xff) {
throw new IOException("Socks Server does not support no-auth");
}
if (buf[1] != 0x00) {
throw new Exception("Socks Server did choose bogus auth");
}

// Request
buf[0] = 0x05; // Version
buf[1] = 0x01; // Connect (TCP)
buf[2] = 0x00; // Reserved
buf[3] = 0x03; // Dest.Addr: Domain name
var domain = Encoding.ASCII.GetBytes("google.com");
buf[4] = (byte)domain.Length; // Domain name length (octet)
Array.Copy(domain, 0, buf, 5, domain.Length);
var port = BitConverter.GetBytes(
IPAddress.HostToNetworkOrder((short)80));
buf[5 + domain.Length] = port[0];
buf[6 + domain.Length] = port[1];
stream.Write(buf, 0, domain.Length + 7);

// Reply
stream.ReadAll(buf, 0, 4);
if (buf[0] != 0x05) {
throw new IOException("Invalid Socks Version");
}
if (buf[1] != 0x00) {
throw new IOException(string.Format("Socks Error {0:X}", buf[1]));
}
var rdest = string.Empty;
switch (buf[3]) {
case 0x01: // IPv4
stream.ReadAll(buf, 0, 4);
var v4 = BitConverter.ToUInt32(buf, 0);
rdest = new IPAddress(v4).ToString();
break;
case 0x03: // Domain name
stream.ReadAll(buf, 0, 1);
if (buf[0] == 0xff) {
throw new IOException("Invalid Domain Name");
}
stream.ReadAll(buf, 1, buf[0]);
rdest = Encoding.ASCII.GetString(buf, 1, buf[0]);
break;
case 0x04: // IPv6
var octets = new byte[16];
stream.ReadAll(octets, 0, 16);
rdest = new IPAddress(octets).ToString();
break;
default:
throw new IOException("Invalid Address type");
}
stream.ReadAll(buf, 0, 2);
var rport = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(buf, 0));
Console.WriteLine("Connected via {0}:{1}", rdest, rport);

// Make an HTTP request, aka. "do stuff ..."
using (var writer = new StreamWriter(stream)) {
writer.Write("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n");
writer.Flush();
using (var reader = new StreamReader(stream)) {
while (true) {
var line = reader.ReadLine();
if (string.IsNullOrEmpty(line)) {
break;
}
}
}
}
}
}
}
}
}

C# connect to URL via proxy fails

you need to say what port your proxy is e.g.

webClient.Proxy = new WebProxy("127.0.0.1:8118");

you also have to actually set up this proxy, webclient.proxy just uses it, it doesn't create it

I'm not entirely sure what the rest of your code is doing, but I don't think you need the

wp.Address = new Uri(@"http://okolje.arso.gov.si/service/prevozniki.zip"); 


Related Topics



Leave a reply



Submit