powered by simpleCommunicator - 2.0.60     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / сокеты и прокси
5 сообщений из 5, страница 1 из 1
сокеты и прокси
    #32846844
gazon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Вот пишу я клиента TCP

Код: plaintext
1.
2.
3.
4.
Socket TempSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(
IPAddress.Parse(AdressOfServer), 9050);
TempSocket.BeginConnect(ipep, new AsyncCallback(Connected), TempSocket);

А что если программа запустится и попытается подконнектиться на компьютере, который имеет выход в интернет через прокси? Мы ведь нигде этого не указываем в подключении в коде. Например браузеру, чтобы он смог коннектиться в интернет указывается в настройках прокси(если комп выходит в инет через прокси), а иначе он не сможет установить соединение. Моя программа я так понимаю тоже не сможет подконнектиться, тогда как с использованием сокетов указать, что выход будет через прокси?
...
Рейтинг: 0 / 0
сокеты и прокси
    #32847330
Фотография Roman S. Golubin
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Боюсь, ни как.
Придется самому писать клиента прокси-сервера.
...
Рейтинг: 0 / 0
сокеты и прокси
    #32848010
gazon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
есть примеры как это сделать?
...
Рейтинг: 0 / 0
сокеты и прокси
    #32848734
Фотография Roman S. Golubin
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Извини за встречный вопрос, но для какого типа прокси-сервера тебя интересует клиент? Или все равно?
...
Рейтинг: 0 / 0
сокеты и прокси
    #32848763
gazon
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Roman S. GolubinИзвини за встречный вопрос, но для какого типа прокси-сервера тебя интересует клиент? Или все равно?
Ну раз у меня TCP клиент, то соответственно интересует прокси SOCKS, а не http.
вот нарыл класс, который реализует оболочку над классом сокет и позволяет выходить в инет через прокси по протоколу SOCKETS5
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
    
/*
* zahmed
* Date 23 Jan 2004
* Socks 5 RFC is available at http://www.faqs.org/rfcs/rfc1928.html.
*/
namespace LMKR
{
public class ConnectionException:ApplicationException
{
public ConnectionException(string message)
	:base(message)
{
}
}

/// <summary>
/// Provides sock5 functionality to clients (Connect only).
/// </summary>
public class SocksProxy
{

private SocksProxy(){} 

#region ErrorMessages
private static string[] errorMsgs=	{
										"Operation completed successfully.",
										"General SOCKS server failure.",
										"Connection not allowed by ruleset.",
										"Network unreachable.",
										"Host unreachable.",
										"Connection refused.",
										"TTL expired.",
										"Command not supported.",
										"Address type not supported.",
										"Unknown error."
									};
#endregion


public static Socket ConnectToSocks5Proxy(string proxyAdress, ushort proxyPort, string destAddress, ushort destPort,
	string userName, string password)
{
	IPAddress destIP = null;
	IPAddress proxyIP = null;
	byte[] request = new byte[257];
	byte[] response = new byte[257];
	ushort nIndex;

	try
	{
		proxyIP =  IPAddress.Parse(proxyAdress);
	}
	catch(FormatException)
	{	// get the IP address
		proxyIP = Dns.GetHostByAddress(proxyAdress).AddressList[0];
	}

	// Parse destAddress (assume it in string dotted format "212.116.65.112" )
	try
	{
		destIP = IPAddress.Parse(destAddress);
	}
	catch(FormatException)
	{
		// wrong assumption its in domain name format "www.microsoft.com"
	}

	IPEndPoint proxyEndPoint = new IPEndPoint(proxyIP,proxyPort);

	// open a TCP connection to SOCKS server...
	Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
	s.Connect(proxyEndPoint);	

	nIndex = 0;
	request[nIndex++]=0x05; // Version 5.
	request[nIndex++]=0x02; // 2 Authentication methods are in packet...
	request[nIndex++]=0x00; // NO AUTHENTICATION REQUIRED
	request[nIndex++]=0x02; // USERNAME/PASSWORD
	// Send the authentication negotiation request...
	s.Send(request,nIndex,SocketFlags.None);

	// Receive 2 byte response...
	int nGot = s.Receive(response,2,SocketFlags.None);	
	if (nGot!=2)
		throw new ConnectionException("Bad response received from proxy server.");

	if (response[1]==0xFF)
	{	// No authentication method was accepted close the socket.
		s.Close();
		throw new ConnectionException("None of the authentication method was accepted by proxy server.");
	}
    
	byte[] rawBytes;

	if (/*response[1]==0x02*/true)
	{//Username/Password Authentication protocol
		nIndex = 0;
		request[nIndex++]=0x05; // Version 5.
    	
		// add user name
		request[nIndex++]=(byte)userName.Length;
		rawBytes = Encoding.Default.GetBytes(userName);
		rawBytes.CopyTo(request,nIndex);
		nIndex+=(ushort)rawBytes.Length;

		// add password
		request[nIndex++]=(byte)password.Length;
		rawBytes = Encoding.Default.GetBytes(password);
		rawBytes.CopyTo(request,nIndex);
		nIndex+=(ushort)rawBytes.Length;

		// Send the Username/Password request
		s.Send(request,nIndex,SocketFlags.None);
		// Receive 2 byte response...
		nGot = s.Receive(response,2,SocketFlags.None);	
		if (nGot!=2)
			throw new ConnectionException("Bad response received from proxy server.");
		if (response[1] != 0x00)
			throw new ConnectionException("Bad Usernaem/Password.");
	}
	// This version only supports connect command. 
	// UDP and Bind are not supported.

	// Send connect request now...
	nIndex = 0;
	request[nIndex++]=0x05;	// version 5.
	request[nIndex++]=0x01;	// command = connect.
	request[nIndex++]=0x00;	// Reserve = must be 0x00

	if (destIP != null)
	{// Destination adress in an IP.
		switch(destIP.AddressFamily)
		{
			case AddressFamily.InterNetwork:
				// Address is IPV4 format
				request[nIndex++]=0x01;
				rawBytes = destIP.GetAddressBytes();
				rawBytes.CopyTo(request,nIndex);
				nIndex+=(ushort)rawBytes.Length;
				break;
			case AddressFamily.InterNetworkV6:
				// Address is IPV6 format
				request[nIndex++]=0x04;
				rawBytes = destIP.GetAddressBytes();
				rawBytes.CopyTo(request,nIndex);
				nIndex+=(ushort)rawBytes.Length;
				break;
		}
	}
	else
	{// Dest. address is domain name.
		request[nIndex++]=0x03;	// Address is full-qualified domain name.
		request[nIndex++]=Convert.ToByte(destAddress.Length); // length of address.
		rawBytes = Encoding.Default.GetBytes(destAddress);
		rawBytes.CopyTo(request,nIndex);
		nIndex+=(ushort)rawBytes.Length;
	}

	// using big-edian byte order
	byte[] portBytes = BitConverter.GetBytes(destPort);
	for (int i=portBytes.Length-1;i>=0;i--)
		request[nIndex++]=portBytes[i];
    
	// send connect request.
	s.Send(request,nIndex,SocketFlags.None);
	s.Receive(response);	// Get variable length response...
	if (response[1]!=0x00)
		throw new ConnectionException(errorMsgs[response[1]]);
	// Success Connected...
	return s;
}
}
}
...
Рейтинг: 0 / 0
5 сообщений из 5, страница 1 из 1
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / сокеты и прокси
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]