Index: IrcConnection/IrcConnection.cs
===================================================================
--- IrcConnection/IrcConnection.cs	(revision 291)
+++ IrcConnection/IrcConnection.cs	(working copy)
@@ -7,7 +7,8 @@
  *
  * SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net>
  *
- * Copyright (c) 2003-2005 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net>
+ * Copyright (c) 2003-2009 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net>
+ * Copyright (c) 2008-2009 Thomas Bruderer <apophis@apophis.ch>
  * 
  * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
  * 
@@ -33,6 +34,8 @@
 using System.Threading;
 using System.Reflection;
 using System.Net.Sockets;
+using System.Net;
+using Org.Mentalis.Network.ProxySocket;
 #if NET_2_0
 using System.Net.Security;
 #endif
@@ -78,6 +81,10 @@
         private DateTime         _LastPingSent;
         private DateTime         _LastPongReceived;
         private TimeSpan         _Lag;
+        private IPEndPoint       _ProxyEndPoint;
+        private ProxyTypes       _ProxyType = ProxyTypes.None;
+        private string           _ProxyUser = "";
+        private string           _ProxyPass = "";
         
         /// <event cref="OnReadLine">
         /// Raised when a \r\n terminated line is read from the socket
@@ -386,6 +393,58 @@
                 return _Lag;
             }
         }
+        
+        /// <summary>
+        /// If you want to use a Proxy, set the ProxyEndPoint to Adress and Port of the Proxy you want to use.
+        /// </summary>
+        public IPEndPoint ProxyEndPoint {
+            get {
+                return _ProxyEndPoint;
+            }
+            set {
+                _ProxyEndPoint = value;
+            }
+        }
+        
+        /// <summary>
+        /// Standard Setting is to use no Proxy Server, if you Set this to any other value, 
+        /// you have to set the ProxyEndPoint aswell (and give credentials if needed)
+        /// Default: Org.Mentalis.Network.ProxySocket.ProxyTypes.None
+        /// </summary>
+        public ProxyTypes ProxyType {
+            get {
+                
+                return _ProxyType;
+            }
+            set {
+                _ProxyType = value;
+            }
+        }
+        
+        /// <summary>
+        /// Username to your Proxy Server
+        /// </summary>
+        public string ProxyUser {
+            get {
+                return _ProxyUser;
+            }
+            set {
+                
+                _ProxyUser = (value!=null)?value:"";
+            }
+        }
+        
+        /// <summary>
+        /// Password to your Proxy Server
+        /// </summary>
+        public string ProxyPass {
+            get {
+                return _ProxyPass;
+            }
+            set {
+                _ProxyPass = (value!=null)?value:"";
+            }
+        }
 
         /// <summary>
         /// Initializes the message queues, read and write thread
@@ -453,16 +512,34 @@
                 OnConnecting(this, EventArgs.Empty);
             }
             try {
-                System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
                 _TcpClient = new IrcTcpClient();
                 _TcpClient.NoDelay = true;
+
+                // Socks 4/5 Proxy
+                ProxySocket socksProxy = new ProxySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                socksProxy.ProxyEndPoint = _ProxyEndPoint;
+                socksProxy.ProxyType = _ProxyType;
+                socksProxy.ProxyUser = _ProxyUser;
+                socksProxy.ProxyPass = _ProxyPass;
+                _TcpClient.Client = socksProxy;
+                
+                
                 _TcpClient.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                 // set timeout, after this the connection will be aborted
                 _TcpClient.ReceiveTimeout = _SocketReceiveTimeout * 1000;
                 _TcpClient.SendTimeout = _SocketSendTimeout * 1000;
-                _TcpClient.Connect(ip, port);
+                if (_ProxyType != ProxyTypes.None) {
+                    //TODO: use multiple ports too!
+                    socksProxy.Connect(Address, port);
+                } else {
+                    // FIXME: this is not needed but should help merging the IPv6 changes! (just use always the if case!)
+                    System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
+                    _TcpClient.Connect(ip, port);
+                }
                 
+                
                 Stream stream = _TcpClient.GetStream();
+
 #if NET_2_0
                 if (_UseSsl) {
                     SslStream sslStream = new SslStream(stream, false, delegate {
Index: SocksProxy/AuthMethod.cs
===================================================================
--- SocksProxy/AuthMethod.cs	(revision 0)
+++ SocksProxy/AuthMethod.cs	(revision 0)
@@ -0,0 +1,113 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace Org.Mentalis.Network.ProxySocket.Authentication {
+	/// <summary>
+	/// Implements a SOCKS authentication scheme.
+	/// </summary>
+	/// <remarks>This is an abstract class; it must be inherited.</remarks>
+	internal abstract class AuthMethod {
+		/// <summary>
+		/// Initializes an AuthMethod instance.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		public AuthMethod(Socket server) {
+			Server = server;
+		}
+		/// <summary>
+		/// Authenticates the user.
+		/// </summary>
+		/// <exception cref="ProxyException">Authentication with the proxy server failed.</exception>
+		/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		public abstract void Authenticate();
+		/// <summary>
+		/// Authenticates the user asynchronously.
+		/// </summary>
+		/// <param name="callback">The method to call when the authentication is complete.</param>
+		/// <exception cref="ProxyException">Authentication with the proxy server failed.</exception>
+		/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		public abstract void BeginAuthenticate(HandShakeComplete callback);
+		/// <summary>
+		/// Gets or sets the socket connection with the proxy server.
+		/// </summary>
+		/// <value>The socket connection with the proxy server.</value>
+		protected Socket Server {
+			get {
+				return m_Server;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_Server = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets a byt array that can be used to store data.
+		/// </summary>
+		/// <value>A byte array to store data.</value>
+		protected byte[] Buffer {
+			get {
+				return m_Buffer;
+			}
+			set {
+				m_Buffer = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the number of bytes that have been received from the remote proxy server.
+		/// </summary>
+		/// <value>An integer that holds the number of bytes that have been received from the remote proxy server.</value>
+		protected int Received {
+			get {
+				return m_Received;
+			}
+			set {
+				m_Received = value;
+			}
+		}
+		// private variables
+		/// <summary>Holds the value of the Buffer property.</summary>
+		private byte[] m_Buffer;
+		/// <summary>Holds the value of the Server property.</summary>
+		private Socket m_Server;
+		/// <summary>Holds the address of the method to call when the proxy has authenticated the client.</summary>
+		protected HandShakeComplete CallBack;
+		/// <summary>Holds the value of the Received property.</summary>
+		private int m_Received;
+	}
+}
\ No newline at end of file
Index: SocksProxy/AuthNone.cs
===================================================================
--- SocksProxy/AuthNone.cs	(revision 0)
+++ SocksProxy/AuthNone.cs	(revision 0)
@@ -0,0 +1,60 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace Org.Mentalis.Network.ProxySocket.Authentication {
+	/// <summary>
+	/// This class implements the 'No Authentication' scheme.
+	/// </summary>
+	internal sealed class AuthNone : AuthMethod {
+		/// <summary>
+		/// Initializes an AuthNone instance.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		public AuthNone(Socket server) : base(server) {}
+		/// <summary>
+		/// Authenticates the user.
+		/// </summary>
+		public override void Authenticate() {
+			return; // Do Nothing
+		}
+		/// <summary>
+		/// Authenticates the user asynchronously.
+		/// </summary>
+		/// <param name="callback">The method to call when the authentication is complete.</param>
+		/// <remarks>This method immediately calls the callback method.</remarks>
+		public override void BeginAuthenticate(HandShakeComplete callback) {
+			callback(null);
+		}
+	}
+}
\ No newline at end of file
Index: SocksProxy/AuthUserPass.cs
===================================================================
--- SocksProxy/AuthUserPass.cs	(revision 0)
+++ SocksProxy/AuthUserPass.cs	(revision 0)
@@ -0,0 +1,157 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+
+namespace Org.Mentalis.Network.ProxySocket.Authentication {
+	/// <summary>
+	/// This class implements the 'username/password authentication' scheme.
+	/// </summary>
+	internal sealed class AuthUserPass : AuthMethod {
+		/// <summary>
+		/// Initializes a new AuthUserPass instance.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		/// <param name="user">The username to use.</param>
+		/// <param name="pass">The password to use.</param>
+		/// <exception cref="ArgumentNullException"><c>user</c> -or- <c>pass</c> is null.</exception>
+		public AuthUserPass(Socket server, string user, string pass) : base(server) {
+			Username = user;
+			Password = pass;
+		}
+		/// <summary>
+		/// Creates an array of bytes that has to be sent if the user wants to authenticate with the username/password authentication scheme.
+		/// </summary>
+		/// <returns>An array of bytes that has to be sent if the user wants to authenticate with the username/password authentication scheme.</returns>
+		private byte[] GetAuthenticationBytes() {
+			byte[] buffer = new byte[3 + Username.Length + Password.Length];
+			buffer[0] = 1;
+			buffer[1] = (byte)Username.Length;
+			Array.Copy(Encoding.ASCII.GetBytes(Username), 0, buffer, 2, Username.Length);
+			buffer[Username.Length + 2] = (byte)Password.Length;
+			Array.Copy(Encoding.ASCII.GetBytes(Password), 0, buffer, Username.Length + 3, Password.Length);
+			return buffer;
+		}
+		/// <summary>
+		/// Starts the authentication process.
+		/// </summary>
+		public override void Authenticate() {
+			Server.Send(GetAuthenticationBytes());
+			byte[] buffer = new byte[2];
+			int received = 0;
+			while (received != 2) {
+				received += Server.Receive(buffer, received, 2 - received, SocketFlags.None);
+			}
+			if (buffer[1] != 0) {
+				Server.Close();
+				throw new ProxyException("Username/password combination rejected.");
+			}
+			return;
+		}
+		/// <summary>
+		/// Starts the asynchronous authentication process.
+		/// </summary>
+		/// <param name="callback">The method to call when the authentication is complete.</param>
+		public override void BeginAuthenticate(HandShakeComplete callback) {
+			CallBack = callback;
+			Server.BeginSend(GetAuthenticationBytes(), 0, 3 + Username.Length + Password.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
+			return;
+		}
+		/// <summary>
+		/// Called when the authentication bytes have been sent.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnSent(IAsyncResult ar) {
+			try {
+				Server.EndSend(ar);
+				Buffer = new byte[2];
+				Server.BeginReceive(Buffer, 0, 2, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
+			} catch (Exception e) {
+				CallBack(e);
+			}
+		}
+		/// <summary>
+		/// Called when the socket received an authentication reply.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnReceive(IAsyncResult ar) {
+			try {
+				Received += Server.EndReceive(ar);
+				if (Received == Buffer.Length)
+					if (Buffer[1] == 0)
+						CallBack(null);
+					else
+						throw new ProxyException("Username/password combination not accepted.");
+				else
+					Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
+			} catch (Exception e) {
+				CallBack(e);
+			}
+		}
+		/// <summary>
+		/// Gets or sets the username to use when authenticating with the proxy server.
+		/// </summary>
+		/// <value>The username to use when authenticating with the proxy server.</value>
+		/// <exception cref="ArgumentNullException">The specified value is null.</exception>
+		private string Username {
+			get {
+				return m_Username;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_Username = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the password to use when authenticating with the proxy server.
+		/// </summary>
+		/// <value>The password to use when authenticating with the proxy server.</value>
+		/// <exception cref="ArgumentNullException">The specified value is null.</exception>
+		private string Password {
+			get {
+				return m_Password;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_Password = value;
+			}
+		}
+		// private variables
+		/// <summary>Holds the value of the Username property.</summary>
+		private string m_Username;
+		/// <summary>Holds the value of the Password property.</summary>
+		private string m_Password;
+	}
+}
\ No newline at end of file
Index: SocksProxy/IAsyncProxyResult.cs
===================================================================
--- SocksProxy/IAsyncProxyResult.cs	(revision 0)
+++ SocksProxy/IAsyncProxyResult.cs	(revision 0)
@@ -0,0 +1,96 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Threading;
+
+namespace Org.Mentalis.Network.ProxySocket {
+	/// <summary>
+	/// A class that implements the IAsyncResult interface. Objects from this class are returned by the BeginConnect method of the ProxySocket class.
+	/// </summary>
+	internal class IAsyncProxyResult : IAsyncResult {
+		/// <summary>Initializes the internal variables of this object</summary>
+		/// <param name="stateObject">An object that contains state information for this request.</param>
+		internal void Init(object stateObject) {
+			m_StateObject = stateObject;
+			m_Completed = false;
+			if (m_WaitHandle != null)
+				m_WaitHandle.Reset();
+		
+		}
+		/// <summary>Initializes the internal variables of this object</summary>
+		internal void Reset() {
+			m_StateObject = null;
+			m_Completed = true;
+			if (m_WaitHandle != null)
+				m_WaitHandle.Set();
+		}
+		/// <summary>Gets a value that indicates whether the server has completed processing the call. It is illegal for the server to use any client supplied resources outside of the agreed upon sharing semantics after it sets the IsCompleted property to "true". Thus, it is safe for the client to destroy the resources after IsCompleted property returns "true".</summary>
+		/// <value>A boolean that indicates whether the server has completed processing the call.</value>
+		public bool IsCompleted {
+			get {
+				return m_Completed;
+			}
+		}
+		/// <summary>Gets a value that indicates whether the BeginXXXX call has been completed synchronously. If this is detected in the AsyncCallback delegate, it is probable that the thread that called BeginInvoke is the current thread.</summary>
+		/// <value>Returns false.</value>
+		public bool CompletedSynchronously {
+			get {
+				return false;
+			}
+		}
+		/// <summary>Gets an object that was passed as the state parameter of the BeginXXXX method call.</summary>
+		/// <value>The object that was passed as the state parameter of the BeginXXXX method call.</value>
+		public object AsyncState {
+			get {
+				return m_StateObject;
+			}
+		}
+		/// <summary>
+		/// The AsyncWaitHandle property returns the WaitHandle that can use to perform a WaitHandle.WaitOne or WaitAny or WaitAll. The object which implements IAsyncResult need not derive from the System.WaitHandle classes directly. The WaitHandle wraps its underlying synchronization primitive and should be signaled after the call is completed. This enables the client to wait for the call to complete instead polling. The Runtime supplies a number of waitable objects that mirror Win32 synchronization primitives e.g. ManualResetEvent, AutoResetEvent and Mutex.
+		/// WaitHandle supplies methods that support waiting for such synchronization objects to become signaled with "any" or "all" semantics i.e. WaitHandle.WaitOne, WaitAny and WaitAll. Such methods are context aware to avoid deadlocks. The AsyncWaitHandle can be allocated eagerly or on demand. It is the choice of the IAsyncResult implementer.
+		///</summary>
+		/// <value>The WaitHandle associated with this asynchronous result.</value>
+		public WaitHandle AsyncWaitHandle {
+			get {
+				if (m_WaitHandle == null)
+					m_WaitHandle = new ManualResetEvent(false);
+				return m_WaitHandle;
+			}
+		}
+		// private variables
+		/// <summary>Used internally to represent the state of the asynchronous request</summary>
+		internal bool m_Completed = true;
+		/// <summary>Holds the value of the StateObject property.</summary>
+		private object m_StateObject;
+		/// <summary>Holds the value of the WaitHandle property.</summary>
+		private ManualResetEvent m_WaitHandle;
+	}
+}
\ No newline at end of file
Index: SocksProxy/ProxyException.cs
===================================================================
--- SocksProxy/ProxyException.cs	(revision 0)
+++ SocksProxy/ProxyException.cs	(revision 0)
@@ -0,0 +1,82 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+
+namespace Org.Mentalis.Network.ProxySocket {
+	/// <summary>
+	/// The exception that is thrown when a proxy error occurs.
+	/// </summary>
+	public class ProxyException : Exception {
+		/// <summary>
+		/// Initializes a new instance of the ProxyException class.
+		/// </summary>
+		public ProxyException() : this("An error occured while talking to the proxy server.") {}
+		/// <summary>
+		/// Initializes a new instance of the ProxyException class.
+		/// </summary>
+		/// <param name="message">The message that describes the error.</param>
+		public ProxyException(string message) : base(message) {}
+		/// <summary>
+		/// Initializes a new instance of the ProxyException class.
+		/// </summary>
+		/// <param name="socks5Error">The error number returned by a SOCKS5 server.</param>
+		public ProxyException(int socks5Error) : this(ProxyException.Socks5ToString(socks5Error)) {}
+		/// <summary>
+		/// Converts a SOCKS5 error number to a human readable string.
+		/// </summary>
+		/// <param name="socks5Error">The error number returned by a SOCKS5 server.</param>
+		/// <returns>A string representation of the specified SOCKS5 error number.</returns>
+		public static string Socks5ToString(int socks5Error) {
+			switch(socks5Error) {
+				case 0:
+					return "Connection succeeded.";
+				case 1:
+					return "General SOCKS server failure.";
+				case 2:
+					return "Connection not allowed by ruleset.";
+				case 3:
+					return "Network unreachable.";
+				case 4:
+					return "Host unreachable.";
+				case 5:
+					return "Connection refused.";
+				case 6:
+					return "TTL expired.";
+				case 7:
+					return "Command not supported.";
+				case 8:
+					return "Address type not supported.";
+				default:
+					return "Unspecified SOCKS error.";
+			}
+		}
+	}
+}
\ No newline at end of file
Index: SocksProxy/ProxySocket.cs
===================================================================
--- SocksProxy/ProxySocket.cs	(revision 0)
+++ SocksProxy/ProxySocket.cs	(revision 0)
@@ -0,0 +1,385 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+// Implements a number of classes to allow Sockets to connect trough a firewall.
+namespace Org.Mentalis.Network.ProxySocket {
+	/// <summary>
+	/// Specifies the type of proxy servers that an instance of the ProxySocket class can use.
+	/// </summary>
+	public enum ProxyTypes {
+		/// <summary>No proxy server; the ProxySocket object behaves exactly like an ordinary Socket object.</summary>
+		None,
+		/// <summary>A SOCKS4[A] proxy server.</summary>
+		Socks4,
+		/// <summary>A SOCKS5 proxy server.</summary>
+		Socks5
+	}
+	/// <summary>
+	/// Implements a Socket class that can connect trough a SOCKS proxy server.
+	/// </summary>
+	/// <remarks>This class implements SOCKS4[A] and SOCKS5.<br>It does not, however, implement the BIND commands, so you cannot .</br></remarks>
+	public class ProxySocket : Socket {
+		/// <summary>
+		/// Initializes a new instance of the ProxySocket class.
+		/// </summary>
+		/// <param name="addressFamily">One of the AddressFamily values.</param>
+		/// <param name="socketType">One of the SocketType values.</param>
+		/// <param name="protocolType">One of the ProtocolType values.</param>
+		/// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
+		public ProxySocket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : this(addressFamily, socketType, protocolType, "") {}
+		/// <summary>
+		/// Initializes a new instance of the ProxySocket class.
+		/// </summary>
+		/// <param name="addressFamily">One of the AddressFamily values.</param>
+		/// <param name="socketType">One of the SocketType values.</param>
+		/// <param name="protocolType">One of the ProtocolType values.</param>
+		/// <param name="proxyUsername">The username to use when authenticating with the proxy server.</param>
+		/// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
+		/// <exception cref="ArgumentNullException"><c>proxyUsername</c> is null.</exception>
+		public ProxySocket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, string proxyUsername) : this(addressFamily, socketType, protocolType, proxyUsername, "") {}
+		/// <summary>
+		/// Initializes a new instance of the ProxySocket class.
+		/// </summary>
+		/// <param name="addressFamily">One of the AddressFamily values.</param>
+		/// <param name="socketType">One of the SocketType values.</param>
+		/// <param name="protocolType">One of the ProtocolType values.</param>
+		/// <param name="proxyUsername">The username to use when authenticating with the proxy server.</param>
+		/// <param name="proxyPassword">The password to use when authenticating with the proxy server.</param>
+		/// <exception cref="SocketException">The combination of addressFamily, socketType, and protocolType results in an invalid socket.</exception>
+		/// <exception cref="ArgumentNullException"><c>proxyUsername</c> -or- <c>proxyPassword</c> is null.</exception>
+		public ProxySocket (AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, string proxyUsername, string proxyPassword) : base(addressFamily, socketType, protocolType) {
+			ProxyUser = proxyUsername;
+			ProxyPass = proxyPassword;
+			ToThrow = new InvalidOperationException();
+		}
+		/// <summary>
+		/// Establishes a connection to a remote device.
+		/// </summary>
+		/// <param name="remoteEP">An EndPoint that represents the remote device.</param>
+		/// <exception cref="ArgumentNullException">The remoteEP parameter is a null reference (Nothing in Visual Basic).</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		/// <exception cref="ProxyException">An error occured while talking to the proxy server.</exception>
+		public new void Connect(EndPoint remoteEP) {
+			if (remoteEP == null)
+				throw new ArgumentNullException("<remoteEP> cannot be null.");
+			if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null)
+				base.Connect(remoteEP);
+			else {
+				base.Connect(ProxyEndPoint);
+				if (ProxyType == ProxyTypes.Socks4)
+					(new Socks4Handler(this, ProxyUser)).Negotiate((IPEndPoint)remoteEP);
+				else if (ProxyType == ProxyTypes.Socks5)
+					(new Socks5Handler(this, ProxyUser, ProxyPass)).Negotiate((IPEndPoint)remoteEP);
+			}
+		}
+		/// <summary>
+		/// Establishes a connection to a remote device.
+		/// </summary>
+		/// <param name="host">The remote host to connect to.</param>
+		/// <param name="port">The remote port to connect to.</param>
+		/// <exception cref="ArgumentNullException">The host parameter is a null reference (Nothing in Visual Basic).</exception>
+		/// <exception cref="ArgumentException">The port parameter is invalid.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		/// <exception cref="ProxyException">An error occured while talking to the proxy server.</exception>
+		/// <remarks>If you use this method with a SOCKS4 server, it will let the server resolve the hostname. Not all SOCKS4 servers support this 'remote DNS' though.</remarks>
+		public void Connect(string host, int port) {
+			if (host == null)
+				throw new ArgumentNullException("<host> cannot be null.");
+			if (port <= 0 || port > 65535)
+				throw new ArgumentException("Invalid port.");
+			if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null)
+				base.Connect(new IPEndPoint(Dns.Resolve(host).AddressList[0], port));
+			else {
+				base.Connect(ProxyEndPoint);
+				if (ProxyType == ProxyTypes.Socks4)
+					(new Socks4Handler(this, ProxyUser)).Negotiate(host, port);
+				else if (ProxyType == ProxyTypes.Socks5)
+					(new Socks5Handler(this, ProxyUser, ProxyPass)).Negotiate(host, port);
+			}
+		}
+		/// <summary>
+		/// Begins an asynchronous request for a connection to a network device.
+		/// </summary>
+		/// <param name="remoteEP">An EndPoint that represents the remote device.</param>
+		/// <param name="callback">The AsyncCallback delegate.</param>
+		/// <param name="state">An object that contains state information for this request.</param>
+		/// <returns>An IAsyncResult that references the asynchronous connection.</returns>
+		/// <exception cref="ArgumentNullException">The remoteEP parameter is a null reference (Nothing in Visual Basic).</exception>
+		/// <exception cref="SocketException">An operating system error occurs while creating the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		public new IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state) {
+			if (remoteEP == null || callback == null)
+				throw new ArgumentNullException();
+			if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null) {
+				return base.BeginConnect(remoteEP, callback, state);
+			} else {
+				CallBack = callback;
+				if (ProxyType == ProxyTypes.Socks4) {
+					AsyncResult = (new Socks4Handler(this, ProxyUser)).BeginNegotiate((IPEndPoint)remoteEP, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
+					return AsyncResult;
+				} else if(ProxyType == ProxyTypes.Socks5) {
+					AsyncResult = (new Socks5Handler(this, ProxyUser, ProxyPass)).BeginNegotiate((IPEndPoint)remoteEP, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
+					return AsyncResult;
+				}
+				return null;
+			}
+		}
+		/// <summary>
+		/// Begins an asynchronous request for a connection to a network device.
+		/// </summary>
+		/// <param name="host">The host to connect to.</param>
+		/// <param name="port">The port on the remote host to connect to.</param>
+		/// <param name="callback">The AsyncCallback delegate.</param>
+		/// <param name="state">An object that contains state information for this request.</param>
+		/// <returns>An IAsyncResult that references the asynchronous connection.</returns>
+		/// <exception cref="ArgumentNullException">The host parameter is a null reference (Nothing in Visual Basic).</exception>
+		/// <exception cref="ArgumentException">The port parameter is invalid.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while creating the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		public IAsyncResult BeginConnect(string host, int port, AsyncCallback callback, object state) {
+			if (host == null || callback == null)
+				throw new ArgumentNullException();
+			if (port <= 0 || port >  65535)
+				throw new ArgumentException();
+			CallBack = callback;
+			if (this.ProtocolType != ProtocolType.Tcp || ProxyType == ProxyTypes.None || ProxyEndPoint == null) {
+				RemotePort = port;
+				AsyncResult = BeginDns(host, new HandShakeComplete(this.OnHandShakeComplete));
+				return AsyncResult;
+			} else {
+				if (ProxyType == ProxyTypes.Socks4) {
+					AsyncResult = (new Socks4Handler(this, ProxyUser)).BeginNegotiate(host, port, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
+					return AsyncResult;
+				} else if(ProxyType == ProxyTypes.Socks5) {
+					AsyncResult = (new Socks5Handler(this, ProxyUser, ProxyPass)).BeginNegotiate(host, port, new HandShakeComplete(this.OnHandShakeComplete), ProxyEndPoint);
+					return AsyncResult;
+				}
+				return null;
+			}
+		}
+		/// <summary>
+		/// Ends a pending asynchronous connection request.
+		/// </summary>
+		/// <param name="asyncResult">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		/// <exception cref="ArgumentNullException">The asyncResult parameter is a null reference (Nothing in Visual Basic).</exception>
+		/// <exception cref="ArgumentException">The asyncResult parameter was not returned by a call to the BeginConnect method.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		/// <exception cref="InvalidOperationException">EndConnect was previously called for the asynchronous connection.</exception>
+		/// <exception cref="ProxyException">The proxy server refused the connection.</exception>
+		public new void EndConnect(IAsyncResult asyncResult) {
+			if (asyncResult == null)
+				throw new ArgumentNullException();
+			if (!asyncResult.IsCompleted)
+				throw new ArgumentException();
+			if (ToThrow != null)
+				throw ToThrow;
+			return;
+		}
+		/// <summary>
+		/// Begins an asynchronous request to resolve a DNS host name or IP address in dotted-quad notation to an IPAddress instance.
+		/// </summary>
+		/// <param name="host">The host to resolve.</param>
+		/// <param name="callback">The method to call when the hostname has been resolved.</param>
+		/// <returns>An IAsyncResult instance that references the asynchronous request.</returns>
+		/// <exception cref="SocketException">There was an error while trying to resolve the host.</exception>
+		internal IAsyncProxyResult BeginDns(string host, HandShakeComplete callback) {
+			try {
+				Dns.BeginResolve(host, new AsyncCallback(this.OnResolved), this);
+				return new IAsyncProxyResult();
+			} catch {
+				throw new SocketException();
+			}
+		}
+		/// <summary>
+		/// Called when the specified hostname has been resolved.
+		/// </summary>
+		/// <param name="asyncResult">The result of the asynchronous operation.</param>
+		private void OnResolved(IAsyncResult asyncResult) {
+			try {
+				IPHostEntry dns = Dns.EndResolve(asyncResult);
+				base.BeginConnect(new IPEndPoint(dns.AddressList[0], RemotePort), new AsyncCallback(this.OnConnect), State);
+			} catch (Exception e) {
+				OnHandShakeComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when the Socket is connected to the remote host.
+		/// </summary>
+		/// <param name="asyncResult">The result of the asynchronous operation.</param>
+		private void OnConnect(IAsyncResult asyncResult) {
+			try {
+				base.EndConnect(asyncResult);
+				OnHandShakeComplete(null);
+			} catch (Exception e) {
+				OnHandShakeComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when the Socket has finished talking to the proxy server and is ready to relay data.
+		/// </summary>
+		/// <param name="error">The error to throw when the EndConnect method is called.</param>
+		private void OnHandShakeComplete(Exception error) {
+			if (error != null)
+				this.Close();
+			ToThrow = error;
+			AsyncResult.Reset();
+			if (CallBack != null)
+				CallBack(AsyncResult);
+		}
+		/// <summary>
+		/// Gets or sets the EndPoint of the proxy server.
+		/// </summary>
+		/// <value>An IPEndPoint object that holds the IP address and the port of the proxy server.</value>
+		public IPEndPoint ProxyEndPoint {
+			get {
+				return m_ProxyEndPoint;
+			}
+			set {
+				m_ProxyEndPoint = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the type of proxy server to use.
+		/// </summary>
+		/// <value>One of the ProxyTypes values.</value>
+		public ProxyTypes ProxyType {
+			get {
+				return m_ProxyType;
+			}
+			set {
+				m_ProxyType = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets a user-defined object.
+		/// </summary>
+		/// <value>The user-defined object.</value>
+		private object State {
+			get {
+				return m_State;
+			}
+			set {
+				m_State = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the username to use when authenticating with the proxy.
+		/// </summary>
+		/// <value>A string that holds the username that's used when authenticating with the proxy.</value>
+		/// <exception cref="ArgumentNullException">The specified value is null.</exception>
+		public string ProxyUser {
+			get {
+				return m_ProxyUser;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_ProxyUser = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the password to use when authenticating with the proxy.
+		/// </summary>
+		/// <value>A string that holds the password that's used when authenticating with the proxy.</value>
+		/// <exception cref="ArgumentNullException">The specified value is null.</exception>
+		public string ProxyPass {
+			get {
+				return m_ProxyPass;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_ProxyPass = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the asynchronous result object.
+		/// </summary>
+		/// <value>An instance of the IAsyncProxyResult class.</value>
+		private IAsyncProxyResult AsyncResult {
+			get {
+				return m_AsyncResult;
+			}
+			set {
+				m_AsyncResult = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the exception to throw when the EndConnect method is called.
+		/// </summary>
+		/// <value>An instance of the Exception class (or subclasses of Exception).</value>
+		private Exception ToThrow {
+			get {
+				return m_ToThrow;
+			}
+			set {
+				m_ToThrow = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the remote port the user wants to connect to.
+		/// </summary>
+		/// <value>An integer that specifies the port the user wants to connect to.</value>
+		private int RemotePort {
+			get {
+				return m_RemotePort;
+			}
+			set {
+				m_RemotePort = value;
+			}
+		}
+		// private variables
+		/// <summary>Holds the value of the State property.</summary>
+		private object m_State;
+		/// <summary>Holds the value of the ProxyEndPoint property.</summary>
+		private IPEndPoint m_ProxyEndPoint = null;
+		/// <summary>Holds the value of the ProxyType property.</summary>
+		private ProxyTypes m_ProxyType = ProxyTypes.None;
+		/// <summary>Holds the value of the ProxyUser property.</summary>
+		private string m_ProxyUser = null;
+		/// <summary>Holds the value of the ProxyPass property.</summary>
+		private string m_ProxyPass = null;
+		/// <summary>Holds a pointer to the method that should be called when the Socket is connected to the remote device.</summary>
+		private AsyncCallback CallBack = null;
+		/// <summary>Holds the value of the AsyncResult property.</summary>
+		private IAsyncProxyResult m_AsyncResult;
+		/// <summary>Holds the value of the ToThrow property.</summary>
+		private Exception m_ToThrow = null;
+		/// <summary>Holds the value of the RemotePort property.</summary>
+		private int m_RemotePort;
+	}
+}
\ No newline at end of file
Index: SocksProxy/Socks4Handler.cs
===================================================================
--- SocksProxy/Socks4Handler.cs	(revision 0)
+++ SocksProxy/Socks4Handler.cs	(revision 0)
@@ -0,0 +1,234 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+
+namespace Org.Mentalis.Network.ProxySocket {
+	/// <summary>
+	/// Implements the SOCKS4[A] protocol.
+	/// </summary>
+	internal sealed class Socks4Handler : SocksHandler {
+		/// <summary>
+		/// Initilizes a new instance of the SocksHandler class.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		/// <param name="user">The username to use when authenticating with the server.</param>
+		/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
+		public Socks4Handler(Socket server, string user) : base(server, user) {}
+		/// <summary>
+		/// Creates an array of bytes that has to be sent when the user wants to connect to a specific host/port combination.
+		/// </summary>
+		/// <param name="host">The host to connect to.</param>
+		/// <param name="port">The port to connect to.</param>
+		/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific host/port combination.</returns>
+		/// <remarks>Resolving the host name will be done at server side. Do note that some SOCKS4 servers do not implement this functionality.</remarks>
+		/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
+		/// <exception cref="ArgumentException"><c>port</c> is invalid.</exception>
+		private byte[] GetHostPortBytes(string host, int port) {
+			if (host == null)
+				throw new ArgumentNullException();
+			if (port <= 0 || port > 65535)
+				throw new ArgumentException();
+			byte [] connect = new byte[10 + Username.Length + host.Length];
+			connect[0] = 4;
+			connect[1] = 1;
+			Array.Copy(PortToBytes(port), 0, connect, 2, 2);
+			connect[4] = connect[5] = connect[6] = 0;
+			connect[7] = 1;
+			Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
+			connect[8 + Username.Length] = 0;
+			Array.Copy(Encoding.ASCII.GetBytes(host), 0, connect, 9 + Username.Length, host.Length);
+			connect[9 + Username.Length + host.Length] = 0;
+			return connect;
+		}
+		/// <summary>
+		/// Creates an array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.
+		/// </summary>
+		/// <param name="remoteEP">The IPEndPoint to connect to.</param>
+		/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.</returns>
+		/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
+		private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
+			if (remoteEP == null)
+				throw new ArgumentNullException();
+			byte [] connect = new byte[9 + Username.Length];
+			connect[0] = 4;
+			connect[1] = 1;
+			Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 2, 2);
+			Array.Copy(AddressToBytes(remoteEP.Address.Address), 0, connect, 4, 4);
+			Array.Copy(Encoding.ASCII.GetBytes(Username), 0, connect, 8, Username.Length);
+			connect[8 + Username.Length] = 0;
+			return connect;
+		}
+		/// <summary>
+		/// Starts negotiating with the SOCKS server.
+		/// </summary>
+		/// <param name="host">The host to connect to.</param>
+		/// <param name="port">The port to connect to.</param>
+		/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
+		/// <exception cref="ArgumentException"><c>port</c> is invalid.</exception>
+		/// <exception cref="ProxyException">The proxy rejected the request.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		public override void Negotiate(string host, int port) {
+			Negotiate(GetHostPortBytes(host, port));
+		}
+		/// <summary>
+		/// Starts negotiating with the SOCKS server.
+		/// </summary>
+		/// <param name="remoteEP">The IPEndPoint to connect to.</param>
+		/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
+		/// <exception cref="ProxyException">The proxy rejected the request.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		public override void Negotiate(IPEndPoint remoteEP) {
+			Negotiate(GetEndPointBytes(remoteEP));
+		}
+		/// <summary>
+		/// Starts negotiating with the SOCKS server.
+		/// </summary>
+		/// <param name="connect">The bytes to send when trying to authenticate.</param>
+		/// <exception cref="ArgumentNullException"><c>connect</c> is null.</exception>
+		/// <exception cref="ArgumentException"><c>connect</c> is too small.</exception>
+		/// <exception cref="ProxyException">The proxy rejected the request.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		private void Negotiate(byte [] connect) {
+			if (connect == null)
+				throw new ArgumentNullException();
+			if (connect.Length < 2)
+				throw new ArgumentException();
+			Server.Send(connect);
+			byte [] buffer = ReadBytes(8);
+			if (buffer[1] != 90) {
+				Server.Close();
+				throw new ProxyException("Negotiation failed.");	
+			}
+		}
+		/// <summary>
+		/// Starts negotiating asynchronously with a SOCKS proxy server.
+		/// </summary>
+		/// <param name="host">The remote server to connect to.</param>
+		/// <param name="port">The remote port to connect to.</param>
+		/// <param name="callback">The method to call when the connection has been established.</param>
+		/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
+		/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
+		public override IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
+			ProtocolComplete = callback;
+			Buffer = GetHostPortBytes(host, port);
+			Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
+			AsyncResult = new IAsyncProxyResult();
+			return AsyncResult;
+		}
+		/// <summary>
+		/// Starts negotiating asynchronously with a SOCKS proxy server.
+		/// </summary>
+		/// <param name="remoteEP">An IPEndPoint that represents the remote device.</param>
+		/// <param name="callback">The method to call when the connection has been established.</param>
+		/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
+		/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
+		public override IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
+			ProtocolComplete = callback;
+			Buffer = GetEndPointBytes(remoteEP);
+			Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
+			AsyncResult = new IAsyncProxyResult();
+			return AsyncResult;
+		}
+		/// <summary>
+		/// Called when the Socket is connected to the remote proxy server.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnConnect(IAsyncResult ar) {
+			try {
+				Server.EndConnect(ar);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				Server.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when the Socket has sent the handshake data.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnSent(IAsyncResult ar) {
+			try {
+				if (Server.EndSend(ar) < Buffer.Length) {
+					ProtocolComplete(new SocketException());
+					return;
+				}
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				Buffer = new byte[8];
+				Received = 0;
+				Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when the Socket has received a reply from the remote proxy server.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnReceive(IAsyncResult ar) {
+			try {
+				int received = Server.EndReceive(ar);
+				if (received <= 0) {
+					ProtocolComplete(new SocketException());
+					return;
+				}
+				Received += received;
+				if (Received == 8) {
+					if (Buffer[1] == 90)
+						ProtocolComplete(null);
+					else {
+						Server.Close();
+						ProtocolComplete(new ProxyException("Negotiation failed."));
+					}
+				} else {
+					Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
+				}
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+	}
+}
+
+
Index: SocksProxy/Socks5Handler.cs
===================================================================
--- SocksProxy/Socks5Handler.cs	(revision 0)
+++ SocksProxy/Socks5Handler.cs	(revision 0)
@@ -0,0 +1,419 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Text;
+using Org.Mentalis.Network.ProxySocket.Authentication;
+
+namespace Org.Mentalis.Network.ProxySocket {
+	/// <summary>
+	/// Implements the SOCKS5 protocol.
+	/// </summary>
+	internal sealed class Socks5Handler : SocksHandler {
+		/// <summary>
+		/// Initiliazes a new Socks5Handler instance.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		/// <exception cref="ArgumentNullException"><c>server</c>  is null.</exception>
+		public Socks5Handler(Socket server) : this(server, "") {}
+		/// <summary>
+		/// Initiliazes a new Socks5Handler instance.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		/// <param name="user">The username to use.</param>
+		/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
+		public Socks5Handler(Socket server, string user) : this(server, user, "") {}
+		/// <summary>
+		/// Initiliazes a new Socks5Handler instance.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		/// <param name="user">The username to use.</param>
+		/// <param name="pass">The password to use.</param>
+		/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> -or- <c>pass</c> is null.</exception>
+		public Socks5Handler(Socket server, string user, string pass) : base(server, user) {
+			Password = pass;
+		}
+		/// <summary>
+		/// Starts the synchronous authentication process.
+		/// </summary>
+		/// <exception cref="ProxyException">Authentication with the proxy server failed.</exception>
+		/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		private void Authenticate() {
+			Server.Send(new byte [] {5, 2, 0, 2});
+			byte[] buffer = ReadBytes(2);
+			if (buffer[1] == 255)
+				throw new ProxyException("No authentication method accepted.");
+			AuthMethod authenticate;
+			switch (buffer[1]) {
+				case 0:
+					authenticate = new AuthNone(Server);
+					break;
+				case 2:
+					authenticate = new AuthUserPass(Server, Username, Password);
+					break;
+				default:
+					throw new ProtocolViolationException();
+			}
+			authenticate.Authenticate();
+		}
+		/// <summary>
+		/// Creates an array of bytes that has to be sent when the user wants to connect to a specific host/port combination.
+		/// </summary>
+		/// <param name="host">The host to connect to.</param>
+		/// <param name="port">The port to connect to.</param>
+		/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific host/port combination.</returns>
+		/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
+		/// <exception cref="ArgumentException"><c>port</c> or <c>host</c> is invalid.</exception>
+		private byte[] GetHostPortBytes(string host, int port) {
+			if (host == null)
+				throw new ArgumentNullException();
+			if (port <= 0 || port > 65535 || host.Length > 255)
+				throw new ArgumentException();
+			byte [] connect = new byte[7 + host.Length];
+			connect[0] = 5;
+			connect[1] = 1;
+			connect[2] = 0; //reserved
+			connect[3] = 3;
+			connect[4] = (byte)host.Length;
+			Array.Copy(Encoding.ASCII.GetBytes(host), 0, connect, 5, host.Length);
+			Array.Copy(PortToBytes(port), 0, connect, host.Length + 5, 2);
+			return connect;
+		}
+		/// <summary>
+		/// Creates an array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.
+		/// </summary>
+		/// <param name="remoteEP">The IPEndPoint to connect to.</param>
+		/// <returns>An array of bytes that has to be sent when the user wants to connect to a specific IPEndPoint.</returns>
+		/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
+		private byte[] GetEndPointBytes(IPEndPoint remoteEP) {
+			if (remoteEP == null)
+				throw new ArgumentNullException();
+			byte [] connect = new byte[10];
+			connect[0] = 5;
+			connect[1] = 1;
+			connect[2] = 0; //reserved
+			connect[3] = 1;
+			Array.Copy(AddressToBytes(remoteEP.Address.Address), 0, connect, 4, 4);
+			Array.Copy(PortToBytes(remoteEP.Port), 0, connect, 8, 2);
+			return connect;
+		}
+		/// <summary>
+		/// Starts negotiating with the SOCKS server.
+		/// </summary>
+		/// <param name="host">The host to connect to.</param>
+		/// <param name="port">The port to connect to.</param>
+		/// <exception cref="ArgumentNullException"><c>host</c> is null.</exception>
+		/// <exception cref="ArgumentException"><c>port</c> is invalid.</exception>
+		/// <exception cref="ProxyException">The proxy rejected the request.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
+		public override void Negotiate(string host, int port) {
+			Negotiate(GetHostPortBytes(host, port));
+		}
+		/// <summary>
+		/// Starts negotiating with the SOCKS server.
+		/// </summary>
+		/// <param name="remoteEP">The IPEndPoint to connect to.</param>
+		/// <exception cref="ArgumentNullException"><c>remoteEP</c> is null.</exception>
+		/// <exception cref="ProxyException">The proxy rejected the request.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
+		public override void Negotiate(IPEndPoint remoteEP) {
+			Negotiate(GetEndPointBytes(remoteEP));
+		}
+		/// <summary>
+		/// Starts negotiating with the SOCKS server.
+		/// </summary>
+		/// <param name="connect">The bytes to send when trying to authenticate.</param>
+		/// <exception cref="ArgumentNullException"><c>connect</c> is null.</exception>
+		/// <exception cref="ArgumentException"><c>connect</c> is too small.</exception>
+		/// <exception cref="ProxyException">The proxy rejected the request.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		/// <exception cref="ProtocolViolationException">The proxy server uses an invalid protocol.</exception>
+		private void Negotiate(byte[] connect) {
+			Authenticate();
+			Server.Send(connect);
+			byte[] buffer = ReadBytes(4);
+			if (buffer[1] != 0) {
+				Server.Close();
+				throw new ProxyException(buffer[1]);
+			}
+			switch(buffer[3]) {
+				case 1:
+					buffer = ReadBytes(6); //IPv4 address with port
+					break;
+				case 3:
+					buffer = ReadBytes(1);
+					buffer = ReadBytes(buffer[0] + 2); //domain name with port
+					break;
+				case 4:
+					buffer = ReadBytes(18); //IPv6 address with port
+					break;
+				default:
+					Server.Close();
+					throw new ProtocolViolationException();
+			}
+		}
+		/// <summary>
+		/// Starts negotiating asynchronously with the SOCKS server. 
+		/// </summary>
+		/// <param name="host">The host to connect to.</param>
+		/// <param name="port">The port to connect to.</param>
+		/// <param name="callback">The method to call when the negotiation is complete.</param>
+		/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
+		/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
+		public override IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
+			ProtocolComplete = callback;
+			HandShake = GetHostPortBytes(host, port);
+			Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
+			AsyncResult = new IAsyncProxyResult();
+			return AsyncResult;
+		}
+		/// <summary>
+		/// Starts negotiating asynchronously with the SOCKS server. 
+		/// </summary>
+		/// <param name="remoteEP">An IPEndPoint that represents the remote device.</param>
+		/// <param name="callback">The method to call when the negotiation is complete.</param>
+		/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
+		/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
+		public override IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint) {
+			ProtocolComplete = callback;
+			HandShake = GetEndPointBytes(remoteEP);
+			Server.BeginConnect(proxyEndPoint, new AsyncCallback(this.OnConnect), Server);
+			AsyncResult = new IAsyncProxyResult();
+			return AsyncResult;
+		}
+		/// <summary>
+		/// Called when the socket is connected to the remote server.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnConnect(IAsyncResult ar) {
+			try {
+				Server.EndConnect(ar);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				Server.BeginSend(new byte [] {5, 2, 0, 2}, 0, 4, SocketFlags.None, new AsyncCallback(this.OnAuthSent), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when the authentication bytes have been sent.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnAuthSent(IAsyncResult ar) {
+			try {
+				Server.EndSend(ar);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				Buffer = new byte[1024];
+				Received = 0;
+				Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnAuthReceive), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when an authentication reply has been received.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnAuthReceive(IAsyncResult ar) {
+			try {
+				Received += Server.EndReceive(ar);
+				if (Received <= 0)
+					throw new SocketException();
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				if (Received < 2) {
+					Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnAuthReceive), Server);
+				} else {
+					AuthMethod authenticate;
+					switch(Buffer[1]) {
+						case 0:
+							authenticate = new AuthNone(Server);
+							break;
+						case 2:
+							authenticate = new AuthUserPass(Server, Username, Password);
+							break;
+						default:
+							ProtocolComplete(new SocketException());
+							return;
+					}
+					authenticate.BeginAuthenticate(new HandShakeComplete(this.OnAuthenticated));
+				}
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when the socket has been successfully authenticated with the server.
+		/// </summary>
+		/// <param name="e">The exception that has occured while authenticating, or <em>null</em> if no error occured.</param>
+		private void OnAuthenticated(Exception e) {
+			if (e != null) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				Server.BeginSend(HandShake, 0, HandShake.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
+			} catch (Exception ex) {
+				ProtocolComplete(ex);
+			}
+		}
+		/// <summary>
+		/// Called when the connection request has been sent.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnSent(IAsyncResult ar) {
+			try {
+				Server.EndSend(ar);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				Buffer = new byte[5];
+				Received = 0;
+				Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Called when a connection reply has been received.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnReceive(IAsyncResult ar) {
+			try {
+				Received += Server.EndReceive(ar);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				if (Received == Buffer.Length)
+					ProcessReply(Buffer);
+				else
+					Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Processes the received reply.
+		/// </summary>
+		/// <param name="buffer">The received reply</param>
+		/// <exception cref="ProtocolViolationException">The received reply is invalid.</exception>
+		private void ProcessReply(byte[] buffer) {
+			switch(buffer[3]) {
+				case 1:
+					Buffer = new byte[5]; //IPv4 address with port - 1 byte
+					break;
+				case 3:
+					Buffer = new byte[buffer[4] + 2]; //domain name with port
+					break;
+				case 4:
+					buffer = new byte[17]; //IPv6 address with port - 1 byte
+					break;
+				default:
+					throw new ProtocolViolationException();
+			}
+			Received = 0;
+			Server.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(this.OnReadLast), Server);
+		}
+		/// <summary>
+		/// Called when the last bytes are read from the socket.
+		/// </summary>
+		/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
+		private void OnReadLast(IAsyncResult ar) {
+			try {
+				Received += Server.EndReceive(ar);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+				return;
+			}
+			try {
+				if (Received == Buffer.Length)
+					ProtocolComplete(null);
+				else
+					Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReadLast), Server);
+			} catch (Exception e) {
+				ProtocolComplete(e);
+			}
+		}
+		/// <summary>
+		/// Gets or sets the password to use when authenticating with the SOCKS5 server.
+		/// </summary>
+		/// <value>The password to use when authenticating with the SOCKS5 server.</value>
+		private string Password {
+			get {
+				return m_Password;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_Password = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the bytes to use when sending a connect request to the proxy server.
+		/// </summary>
+		/// <value>The array of bytes to use when sending a connect request to the proxy server.</value>
+		private byte[] HandShake {
+			get {
+				return m_HandShake;
+			}
+			set {
+				m_HandShake = value;
+			}
+		}
+		// private variables
+		/// <summary>Holds the value of the Password property.</summary>
+		private string m_Password;
+		/// <summary>Holds the value of the HandShake property.</summary>
+		private byte[] m_HandShake;
+	}
+}
\ No newline at end of file
Index: SocksProxy/SocksHandler.cs
===================================================================
--- SocksProxy/SocksHandler.cs	(revision 0)
+++ SocksProxy/SocksHandler.cs	(revision 0)
@@ -0,0 +1,204 @@
+/*
+    Copyright © 2002, The KPD-Team
+    All rights reserved.
+    http://www.mentalis.org/
+
+  Redistribution and use in source and binary forms, with or without
+  modification, are permitted provided that the following conditions
+  are met:
+
+    - Redistributions of source code must retain the above copyright
+       notice, this list of conditions and the following disclaimer. 
+
+    - Neither the name of the KPD-Team, nor the names of its contributors
+       may be used to endorse or promote products derived from this
+       software without specific prior written permission. 
+
+  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+  THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+  OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+using System;
+using System.Net;
+using System.Net.Sockets;
+
+namespace Org.Mentalis.Network.ProxySocket {
+	/// <summary>
+	/// References the callback method to be called when the protocol negotiation is completed.
+	/// </summary>
+	internal delegate void HandShakeComplete(Exception error);
+	/// <summary>
+	/// Implements a specific version of the SOCKS protocol. This is an abstract class; it must be inherited.
+	/// </summary>
+	internal abstract class SocksHandler {
+		/// <summary>
+		/// Initilizes a new instance of the SocksHandler class.
+		/// </summary>
+		/// <param name="server">The socket connection with the proxy server.</param>
+		/// <param name="user">The username to use when authenticating with the server.</param>
+		/// <exception cref="ArgumentNullException"><c>server</c> -or- <c>user</c> is null.</exception>
+		public SocksHandler(Socket server, string user) {
+			Server = server;
+			Username = user;
+		}
+		/// <summary>
+		/// Converts a port number to an array of bytes.
+		/// </summary>
+		/// <param name="port">The port to convert.</param>
+		/// <returns>An array of two bytes that represents the specified port.</returns>
+		protected byte[] PortToBytes(int port) {
+			byte [] ret = new byte[2];
+			ret[0] = (byte)(port / 256);
+			ret[1] = (byte)(port % 256);
+			return ret;
+		}
+		/// <summary>
+		/// Converts an IP address to an array of bytes.
+		/// </summary>
+		/// <param name="address">The IP address to convert.</param>
+		/// <returns>An array of four bytes that represents the specified IP address.</returns>
+		protected byte[] AddressToBytes(long address) {
+			byte [] ret = new byte[4];
+			ret[0] = (byte)(address % 256);
+			ret[1] = (byte)((address / 256) % 256);
+			ret[2] = (byte)((address / 65536) % 256);
+			ret[3] = (byte)(address / 16777216);
+			return ret;
+		}
+		/// <summary>
+		/// Reads a specified number of bytes from the Server socket.
+		/// </summary>
+		/// <param name="count">The number of bytes to return.</param>
+		/// <returns>An array of bytes.</returns>
+		/// <exception cref="ArgumentException">The number of bytes to read is invalid.</exception>
+		/// <exception cref="SocketException">An operating system error occurs while accessing the Socket.</exception>
+		/// <exception cref="ObjectDisposedException">The Socket has been closed.</exception>
+		protected byte[] ReadBytes(int count) {
+			if (count <= 0)
+				throw new ArgumentException();
+			byte[] buffer = new byte[count];
+			int received = 0;
+			while(received != count) {
+				received += Server.Receive(buffer, received, count - received, SocketFlags.None);
+			}
+			return buffer;
+		}
+		/// <summary>
+		/// Gets or sets the socket connection with the proxy server.
+		/// </summary>
+		/// <value>A Socket object that represents the connection with the proxy server.</value>
+		/// <exception cref="ArgumentNullException">The specified value is null.</exception>
+		protected Socket Server {
+			get {
+				return m_Server;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_Server = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the username to use when authenticating with the proxy server.
+		/// </summary>
+		/// <value>A string that holds the username to use when authenticating with the proxy server.</value>
+		/// <exception cref="ArgumentNullException">The specified value is null.</exception>
+		protected string Username {
+			get {
+				return m_Username;
+			}
+			set {
+				if (value == null)
+					throw new ArgumentNullException();
+				m_Username = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the return value of the BeginConnect call.
+		/// </summary>
+		/// <value>An IAsyncProxyResult object that is the return value of the BeginConnect call.</value>
+		protected IAsyncProxyResult AsyncResult {
+			get {
+				return m_AsyncResult;
+			}
+			set {
+				m_AsyncResult = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets a byte buffer.
+		/// </summary>
+		/// <value>An array of bytes.</value>
+		protected byte[] Buffer {
+			get {
+				return m_Buffer;
+			}
+			set {
+				m_Buffer = value;
+			}
+		}
+		/// <summary>
+		/// Gets or sets the number of bytes that have been received from the remote proxy server.
+		/// </summary>
+		/// <value>An integer that holds the number of bytes that have been received from the remote proxy server.</value>
+		protected int Received {
+			get {
+				return m_Received;
+			}
+			set {
+				m_Received = value;
+			}
+		}
+		// private variables
+		/// <summary>Holds the value of the Server property.</summary>
+		private Socket m_Server;
+		/// <summary>Holds the value of the Username property.</summary>
+		private string m_Username;
+		/// <summary>Holds the value of the AsyncResult property.</summary>
+		private IAsyncProxyResult m_AsyncResult;
+		/// <summary>Holds the value of the Buffer property.</summary>
+		private byte[] m_Buffer;
+		/// <summary>Holds the value of the Received property.</summary>
+		private int m_Received;
+		/// <summary>Holds the address of the method to call when the SOCKS protocol has been completed.</summary>
+		protected HandShakeComplete ProtocolComplete;
+		/// <summary>
+		/// Starts negotiating with a SOCKS proxy server.
+		/// </summary>
+		/// <param name="host">The remote server to connect to.</param>
+		/// <param name="port">The remote port to connect to.</param>
+		public abstract void Negotiate(string host, int port);
+		/// <summary>
+		/// Starts negotiating with a SOCKS proxy server.
+		/// </summary>
+		/// <param name="remoteEP">The remote endpoint to connect to.</param>
+		public abstract void Negotiate(IPEndPoint remoteEP);
+		/// <summary>
+		/// Starts negotiating asynchronously with a SOCKS proxy server.
+		/// </summary>
+		/// <param name="remoteEP">An IPEndPoint that represents the remote device. </param>
+		/// <param name="callback">The method to call when the connection has been established.</param>
+		/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
+		/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
+		public abstract IAsyncProxyResult BeginNegotiate(IPEndPoint remoteEP, HandShakeComplete callback, IPEndPoint proxyEndPoint);
+		/// <summary>
+		/// Starts negotiating asynchronously with a SOCKS proxy server.
+		/// </summary>
+		/// <param name="host">The remote server to connect to.</param>
+		/// <param name="port">The remote port to connect to.</param>
+		/// <param name="callback">The method to call when the connection has been established.</param>
+		/// <param name="proxyEndPoint">The IPEndPoint of the SOCKS proxy server.</param>
+		/// <returns>An IAsyncProxyResult that references the asynchronous connection.</returns>
+		public abstract IAsyncProxyResult BeginNegotiate(string host, int port, HandShakeComplete callback, IPEndPoint proxyEndPoint);
+	}
+}
\ No newline at end of file
