using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Text;
class Program
{
static async Task Main()
{
var url = new Uri("https://ipv4.icanhazip.com");
var proxy = new Uri("http://unblocker.iproyal.com:12323");
const string proxyUser = "username";
const string proxyPass = "password";
using var client = CreateHttpClient(proxy, proxyUser, proxyPass);
var ip = (await client.GetStringAsync(url)).Trim();
Console.WriteLine(ip);
}
private static HttpClient CreateHttpClient(Uri proxyUri, string user, string pass)
{
var handler = new SocketsHttpHandler
{
AllowAutoRedirect = true,
AutomaticDecompression = DecompressionMethods.All,
SslOptions = new SslClientAuthenticationOptions
{
RemoteCertificateValidationCallback = static (_, _, _, _) => true
},
ConnectCallback = async (ctx, ct) =>
{
var tcp = new TcpClient();
await tcp.ConnectAsync(proxyUri.Host, proxyUri.Port);
var stream = tcp.GetStream();
var auth = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{user}:{pass}"));
string host = ctx.DnsEndPoint.Host;
int port = ctx.DnsEndPoint.Port;
var request =
$"CONNECT {host}:{port} HTTP/1.1\r\n" +
$"Host: {host}:{port}\r\n" +
$"Proxy-Authorization: Basic {auth}\r\n" +
"\r\n";
var bytes = Encoding.ASCII.GetBytes(request);
await stream.WriteAsync(bytes, 0, bytes.Length, ct);
await stream.FlushAsync(ct);
using var reader = new StreamReader(stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: false, bufferSize: 4096, leaveOpen: true);
var status = await reader.ReadLineAsync();
if (status is null || !status.Contains(" 200 "))
throw new IOException($"Proxy CONNECT failed: {status}");
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) { }
return stream;
}
};
var client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
client.DefaultRequestVersion = HttpVersion.Version11;
return client;
}
}