Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- namespace COMail
- {
- 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 ConnectToSocks(string proxyAdress, ushort proxyPort)
- {
- 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];
- }
- 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++] = 0x00; // 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.");
- }
- // Send connect request now...
- nIndex = 0;
- request[nIndex++] = 0x05; // version 5.
- request[nIndex++] = 0x01; // command = connect.
- request[nIndex++] = 0x00; // Reserve = must be 0x00
- // 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;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment