After purchasing static IP services from IPNut platform, use the following C# code samples for integration.
1. SOCKS5 Proxy Example #
/**
* SOCKS5 Proxy Demo - C#
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ProxyDemo
{
public class Socks5ProxyDemo
{
private readonly string proxyHost = "proxy.ipnut.com";
private readonly int proxyPort = 28001;
private readonly string proxyUsername = "ipnut";
private readonly string proxyPassword = "123456789";
/**
* Connect to SOCKS5 proxy server
*/
private async Task ConnectToSocks5ProxyAsync()
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Resolve proxy server address
var hostEntry = await Dns.GetHostEntryAsync(proxyHost);
var proxyEndPoint = new IPEndPoint(hostEntry.AddressList[0], proxyPort);
await socket.ConnectAsync(proxyEndPoint);
Console.WriteLine("Successfully connected to SOCKS5 proxy server");
return socket;
}
catch (Exception ex)
{
Console.WriteLine($"Failed to connect to proxy server: {ex.Message}");
return null;
}
}
/**
* SOCKS5 authentication handshake
*/
private async Task Socks5AuthenticateAsync(Socket socket)
{
try
{
// SOCKS5 handshake packet
byte[] handshake = new byte[]
{
0x05, // SOCKS version 5
0x02, // Number of authentication methods
0x00, // No authentication
0x02 // Username/password authentication
};
await socket.SendAsync(new ArraySegment(handshake), SocketFlags.None);
// Receive server response
byte[] response = new byte[2];
int bytesReceived = await socket.ReceiveAsync(new ArraySegment(response), SocketFlags.None);
if (bytesReceived < 2)
{
Console.WriteLine("Failed to receive handshake response");
return false;
}
if (response[0] != 0x05)
{
Console.WriteLine("Unsupported SOCKS version");
return false;
}
// If username/password authentication is required
if (response[1] == 0x02)
{
return await Socks5UsernamePasswordAuthAsync(socket);
}
else if (response[1] != 0x00)
{
Console.WriteLine($"Unsupported authentication method: {response[1]}");
return false;
}
return true;
}
catch (Exception ex)
{
Console.WriteLine($"SOCKS5 authentication failed: {ex.Message}");
return false;
}
}
/**
* SOCKS5 username/password authentication
*/
private async Task Socks5UsernamePasswordAuthAsync(Socket socket)
{
try
{
var authPacket = new System.Collections.Generic.List();
authPacket.Add(0x01); // Authentication version
authPacket.Add((byte)proxyUsername.Length);
authPacket.AddRange(Encoding.UTF8.GetBytes(proxyUsername));
authPacket.Add((byte)proxyPassword.Length);
authPacket.AddRange(Encoding.UTF8.GetBytes(proxyPassword));
await socket.SendAsync(new ArraySegment(authPacket.ToArray()), SocketFlags.None);
byte[] authResponse = new byte[2];
int bytesReceived = await socket.ReceiveAsync(new ArraySegment(authResponse), SocketFlags.None);
if (bytesReceived < 2)
{
Console.WriteLine("Failed to receive authentication response");
return false;
}
if (authResponse[0] != 0x01 || authResponse[1] != 0x00)
{
Console.WriteLine("SOCKS5 authentication failed");
return false;
}
Console.WriteLine("SOCKS5 authentication successful");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"Username/password authentication failed: {ex.Message}");
return false;
}
}
/**
* Connect to target server through SOCKS5 proxy
*/
private async Task Socks5ConnectToTargetAsync(Socket socket, string targetHost, int targetPort)
{
try
{
var connectPacket = new System.Collections.Generic.List();
connectPacket.Add(0x05); // SOCKS version
connectPacket.Add(0x01); // CONNECT command
connectPacket.Add(0x00); // Reserved
// Domain name type
connectPacket.Add(0x03); // Domain name
connectPacket.Add((byte)targetHost.Length);
connectPacket.AddRange(Encoding.UTF8.GetBytes(targetHost));
// Port
connectPacket.Add((byte)((targetPort >> 8) & 0xFF));
connectPacket.Add((byte)(targetPort & 0xFF));
await socket.SendAsync(new ArraySegment(connectPacket.ToArray()), SocketFlags.None);
// Receive connection response
byte[] connectResponse = new byte[10];
int bytesReceived = await socket.ReceiveAsync(new ArraySegment(connectResponse), SocketFlags.None);
if (bytesReceived < 2)
{
Console.WriteLine("Failed to receive connection response");
return false;
}
if (connectResponse[0] != 0x05 || connectResponse[1] != 0x00)
{
Console.WriteLine($"SOCKS5 connection failed, code: {connectResponse[1]}");
return false;
}
Console.WriteLine("Successfully connected to target server through SOCKS5 proxy");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"SOCKS5 connection to target failed: {ex.Message}");
return false;
}
}
/**
* Send HTTP request through SOCKS5 proxy
*/
public async Task SendHttpRequestViaSocks5Async(string targetHost, int targetPort, string path = "/ip")
{
Console.WriteLine($"=== Send HTTP Request via SOCKS5 Proxy ===");
var socket = await ConnectToSocks5ProxyAsync();
if (socket == null) return;
try
{
if (!await Socks5AuthenticateAsync(socket))
return;
if (!await Socks5ConnectToTargetAsync(socket, targetHost, targetPort))
return;
// Send HTTP request
string httpRequest =
$"GET {path} HTTP/1.1\r\n" +
$"Host: {targetHost}\r\n" +
"User-Agent: CSharp-SOCKS5-Proxy/1.0\r\n" +
"Connection: close\r\n" +
"\r\n";
byte[] requestBytes = Encoding.UTF8.GetBytes(httpRequest);
await socket.SendAsync(new ArraySegment(requestBytes), SocketFlags.None);
// Receive HTTP response
Console.WriteLine("HTTP Response:");
byte[] buffer = new byte[4096];
int bytesReceived;
while ((bytesReceived = await socket.ReceiveAsync(new ArraySegment(buffer), SocketFlags.None)) > 0)
{
string response = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
Console.Write(response);
}
Console.WriteLine();
}
catch (Exception ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
}
finally
{
socket?.Close();
}
}
/**
* Use HttpClient with SOCKS5 proxy
*/
public async Task UseHttpClientWithSocks5Async()
{
Console.WriteLine("=== Use HttpClient with SOCKS5 Proxy ===");
try
{
// Create custom HttpClientHandler using SOCKS5 proxy
var handler = new HttpClientHandler
{
Proxy = new WebProxy($"socks5://{proxyUsername}:{proxyPassword}@{proxyHost}:{proxyPort}"),
UseProxy = true
};
using var httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(30);
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("CSharp-SOCKS5-HttpClient/1.0");
var response = await httpClient.GetAsync("http://httpbin.org/ip");
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status Code: {response.StatusCode}");
Console.WriteLine($"Response Content: {content}");
}
catch (Exception ex)
{
Console.WriteLine($"HttpClient request failed: {ex.Message}");
}
}
/**
* Run SOCKS5 demo
*/
public async Task RunDemoAsync()
{
Console.WriteLine("Starting SOCKS5 proxy test...\n");
// Test Socket method
await SendHttpRequestViaSocks5Async("httpbin.org", 80, "/ip");
await SendHttpRequestViaSocks5Async("httpbin.org", 80, "/user-agent");
await SendHttpRequestViaSocks5Async("httpbin.org", 80, "/headers");
// Test HttpClient method
await UseHttpClientWithSocks5Async();
Console.WriteLine("SOCKS5 proxy test completed!");
}
}
}
2. HTTP Proxy Example #
/**
* HTTP Proxy Demo - C#
*/
using System;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ProxyDemo
{
public class HttpProxyDemo
{
private readonly string proxyHost = "proxy.ipnut.com";
private readonly int proxyPort = 28001;
private readonly string proxyUsername = "ipnut";
private readonly string proxyPassword = "123456789";
/**
* Use HttpClient with HTTP proxy
*/
public async Task UseHttpClientWithHttpProxyAsync()
{
Console.WriteLine("=== Use HttpClient with HTTP Proxy ===");
try
{
// Create proxy credentials
var proxy = new WebProxy($"http://{proxyHost}:{proxyPort}")
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword)
};
var handler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true,
PreAuthenticate = true
};
using var httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(30);
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("CSharp-HTTP-Proxy/1.0");
// Test multiple endpoints
string[] testUrls = {
"http://httpbin.org/ip",
"http://httpbin.org/user-agent",
"http://httpbin.org/headers"
};
foreach (string url in testUrls)
{
Console.WriteLine($"\nRequest: {url}");
try
{
var response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status Code: {response.StatusCode}");
Console.WriteLine($"Response Content: {content}");
}
catch (Exception ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
}
await Task.Delay(1000); // Avoid sending requests too fast
}
}
catch (Exception ex)
{
Console.WriteLine($"HttpClient request failed: {ex.Message}");
}
}
/**
* Use WebClient with HTTP proxy
*/
public async Task UseWebClientWithHttpProxyAsync()
{
Console.WriteLine("\n=== Use WebClient with HTTP Proxy ===");
try
{
using var webClient = new WebClient();
// Set proxy
webClient.Proxy = new WebProxy($"http://{proxyHost}:{proxyPort}")
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword)
};
webClient.Headers["User-Agent"] = "CSharp-WebClient-Proxy/1.0";
webClient.Headers["Accept"] = "application/json";
string response = await webClient.DownloadStringTaskAsync("http://httpbin.org/ip");
Console.WriteLine($"Response Content: {response}");
}
catch (Exception ex)
{
Console.WriteLine($"WebClient request failed: {ex.Message}");
}
}
/**
* Use Socket with HTTP proxy (CONNECT method)
*/
public async Task UseSocketWithHttpProxyAsync()
{
Console.WriteLine("\n=== Use Socket with HTTP Proxy (CONNECT Method) ===");
Socket socket = null;
try
{
// Connect to proxy server
var hostEntry = await Dns.GetHostEntryAsync(proxyHost);
var proxyEndPoint = new IPEndPoint(hostEntry.AddressList[0], proxyPort);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await socket.ConnectAsync(proxyEndPoint);
Console.WriteLine("Successfully connected to HTTP proxy server");
// Build authentication information
string auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{proxyUsername}:{proxyPassword}"));
// Send CONNECT request
string connectRequest =
$"CONNECT httpbin.org:80 HTTP/1.1\r\n" +
$"Host: httpbin.org:80\r\n" +
$"Proxy-Authorization: Basic {auth}\r\n" +
$"User-Agent: CSharp-Socket-Proxy/1.0\r\n" +
$"Connection: keep-alive\r\n" +
$"\r\n";
byte[] requestBytes = Encoding.UTF8.GetBytes(connectRequest);
await socket.SendAsync(new ArraySegment(requestBytes), SocketFlags.None);
// Read proxy response
byte[] buffer = new byte[4096];
int bytesReceived = await socket.ReceiveAsync(new ArraySegment(buffer), SocketFlags.None);
string response = Encoding.UTF8.GetString(buffer, 0, bytesReceived);
if (!response.Contains("200 Connection established"))
{
Console.WriteLine($"Proxy connection failed: {response}");
return;
}
Console.WriteLine("Successfully connected to target server through HTTP proxy");
// Send HTTP request
string httpRequest =
"GET /ip HTTP/1.1\r\n" +
"Host: httpbin.org\r\n" +
"User-Agent: CSharp-Socket-Proxy/1.0\r\n" +
"Connection: close\r\n" +
"\r\n";
byte[] httpRequestBytes = Encoding.UTF8.GetBytes(httpRequest);
await socket.SendAsync(new ArraySegment(httpRequestBytes), SocketFlags.None);
// Read HTTP response
Console.WriteLine("HTTP Response:");
StringBuilder responseBuilder = new StringBuilder();
while ((bytesReceived = await socket.ReceiveAsync(new ArraySegment(buffer), SocketFlags.None)) > 0)
{
responseBuilder.Append(Encoding.UTF8.GetString(buffer, 0, bytesReceived));
}
Console.WriteLine(responseBuilder.ToString());
}
catch (Exception ex)
{
Console.WriteLine($"Socket request failed: {ex.Message}");
}
finally
{
socket?.Close();
}
}
/**
* HTTP proxy POST request demo
*/
public async Task HttpProxyPostRequestAsync()
{
Console.WriteLine("\n=== HTTP Proxy POST Request Demo ===");
try
{
var proxy = new WebProxy($"http://{proxyHost}:{proxyPort}")
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword)
};
var handler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
using var httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(30);
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("CSharp-HTTP-POST-Proxy/1.0");
var postData = new
{
name = "ipnut_user",
email = "user@ipnut.com",
message = "Test HTTP proxy POST request"
};
string json = System.Text.Json.JsonSerializer.Serialize(postData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://httpbin.org/post", content);
response.EnsureSuccessStatusCode();
string responseContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Status Code: {response.StatusCode}");
Console.WriteLine($"Response Content: {responseContent}");
}
catch (Exception ex)
{
Console.WriteLine($"POST request failed: {ex.Message}");
}
}
/**
* Run HTTP proxy demo
*/
public async Task RunDemoAsync()
{
Console.WriteLine("Starting HTTP proxy test...\n");
await UseHttpClientWithHttpProxyAsync();
await UseWebClientWithHttpProxyAsync();
await UseSocketWithHttpProxyAsync();
await HttpProxyPostRequestAsync();
Console.WriteLine("HTTP proxy test completed!");
}
}
}
3. Proxy Testing Tool #
/**
* Proxy Testing Tool - C#
*/
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace ProxyDemo
{
public class ProxyTestTool
{
private readonly string proxyHost = "proxy.ipnut.com";
private readonly int proxyPort = 28001;
private readonly string proxyUsername = "ipnut";
private readonly string proxyPassword = "123456789";
/**
* Test SOCKS5 proxy
*/
public async Task TestSocks5ProxyAsync()
{
Console.WriteLine("Test SOCKS5 Proxy:");
try
{
var handler = new HttpClientHandler
{
Proxy = new WebProxy($"socks5://{proxyUsername}:{proxyPassword}@{proxyHost}:{proxyPort}"),
UseProxy = true
};
using var httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(15);
var response = await httpClient.GetAsync("http://httpbin.org/ip");
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("✅ SOCKS5 Proxy connection successful");
Console.WriteLine($" Status Code: {response.StatusCode}");
Console.WriteLine($" Current IP: {content}");
}
catch (Exception ex)
{
Console.WriteLine($"❌ SOCKS5 Proxy connection failed: {ex.Message}");
}
}
/**
* Test HTTP proxy
*/
public async Task TestHttpProxyAsync()
{
Console.WriteLine("\nTest HTTP Proxy:");
try
{
var proxy = new WebProxy($"http://{proxyHost}:{proxyPort}")
{
Credentials = new NetworkCredential(proxyUsername, proxyPassword)
};
var handler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
using var httpClient = new HttpClient(handler);
httpClient.Timeout = TimeSpan.FromSeconds(15);
var response = await httpClient.GetAsync("http://httpbin.org/ip");
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("✅ HTTP Proxy connection successful");
Console.WriteLine($" Status Code: {response.StatusCode}");
Console.WriteLine($" Current IP: {content}");
}
catch (Exception ex)
{
Console.WriteLine($"❌ HTTP Proxy connection failed: {ex.Message}");
}
}
/**
* Run tests
*/
public async Task RunTestsAsync()
{
Console.WriteLine("=== Proxy Testing Tool ===\n");
await TestSocks5ProxyAsync();
await TestHttpProxyAsync();
Console.WriteLine("\nProxy testing completed!");
}
}
}
4. Main Program File #
/**
* Main Program - Proxy Demo Entry Point
*/
using System;
using System.Threading.Tasks;
namespace ProxyDemo
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("C# Proxy Connection Demo Program");
Console.WriteLine("================================\n");
// Run proxy testing tool
var testTool = new ProxyTestTool();
await testTool.RunTestsAsync();
Console.WriteLine("\n" + new string('=', 50) + "\n");
// Run SOCKS5 demo
var socks5Demo = new Socks5ProxyDemo();
await socks5Demo.RunDemoAsync();
Console.WriteLine("\n" + new string('=', 50) + "\n");
// Run HTTP demo
var httpDemo = new HttpProxyDemo();
await httpDemo.RunDemoAsync();
Console.WriteLine("\nAll demos completed!");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
5. Project Configuration File #
Exe
net6.0
enable
enable
6. Compilation and Execution Instructions #
# 1. Create new project
dotnet new console -n ProxyDemo
cd ProxyDemo
# 2. Add the above code files to the project, then compile and run:
# bash
# Compile project
dotnet build
# 2. Run program
dotnet run
# 3. Release version
dotnet publish -c Release
# 4. Run complete demo:
# bash
dotnet run
# 5. Run SOCKS5 demo only:
# csharp
// In Program.cs, comment out other parts, keep only:
var socks5Demo = new Socks5ProxyDemo();
await socks5Demo.RunDemoAsync();
# 6. Run HTTP demo only:
# csharp
// In Program.cs, comment out other parts, keep only:
var httpDemo = new HttpProxyDemo();
await httpDemo.RunDemoAsync();
Technical Support
For integration assistance or location-specific requirements:
Email: Support@ipnut.com
Live Chat: 24/7 real-time support via official website
*All code examples support both HTTP and SOCKS5 protocols with enterprise-grade authentication and security features.*