C# Basic Socket Programming Building Proxy Server

What is Proxy Server?

In computer networks, a proxy server is a server (a computer system or an application program) that acts as an intermediary for requests from clients seeking resources from other servers. A client connects to the proxy server, requesting some service, such as a file, connection, web page, or other resource, available from a different server. The proxy server evaluates the request according to its filtering rules. For example, it may filter traffic by IP address or protocol. If the request is validated by the filter, the proxy provides the resource by connecting to the relevant server and requesting the service on behalf of the client. A proxy server may optionally alter the client’s request or the server’s response, and sometimes it may serve the request without contacting the specified server. In this case, it ‘caches’ responses from the remote server, and returns subsequent requests for the same content directly.

What is Socket?

a software object that connects an application to a network protocol. In UNIX, for example, a program can send and receive TCP/IP messages by opening a socket and reading and writing data to and from the socket. This simplifies program development because the programmer need only worry about manipulating the socket and can rely on the operating system to actually transport messages across the network correctly. Note that a socket in this sense is completely soft – it’s a software object, not a physical component.


How can we build proxy server by using c# socket?

A proxy server is both a web server and a web client, and does the following:

  • S1: listens for HTTP traffic,
  • S2: receives requests
  • C1: sends requests to the server
  • C2: receives response from the server
  • S3: sends response to the client.

S: always receive requests from clients and send server response back to the client

C: request to the real server and send the response to the S

Step One: Build S

const int BACKLOG = 100;

Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, portnumber);
IPAddress ipAddress = IPAddress.Loopback;
listener.Bind(localEndPoint);
listener.Listen(BACKLOG);

while (true)
{
	Socket sock = listener.Accept();
	RequestHandler rh = new RequestHandler();
	Thread requestThread = new Thread(new ThreadStart(rh.Handle));
	requestThread.Start();
}

Step Two: Build C

public class RequestHandler
{
	//Server Socket
	private Socket serverSocket;

	public class RequestHandler(Socket serverSocket)
	{
		this.serverSocket = serverSocket;
	}

	public void Handle()
	{
		//Get and Analyze Client Request
		string header = GetHeader(serverSocket);
		string host = AnalyzeHeader(header);

		//Build C_Socket (client Socket)
		Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		IPAddress[] addresslist = Dns.GetHostAddresses(host);
		IPEndPoint remoteEP = new IPEndPoint (addresslist[0], 80);
		clientSocket.Connect (remoteEP);

		//Send Client Request to the real server
		SendRequest(clientSocket, header);

		//Receive Response from the real server through client socket
		header = GetHeader(clientSocket);

		//Send the real server response to the client through server socket
		SendRequest(serverSocket, header);
		int receivedBytes = 0;
		const int BUFSZ = 1024;
		byte[] buffer = new byte[BUFSZ];
		receivedBytes = clientSocket.Receive(buffer);
		while(receivedBytes > 0)
		{
			this.serverSocket.Send(buffer, receivedBytes, SocketFlags.None);
			receivedBytes = clientSocket.Receive(buffer);
		}

		//Shutdown and close the server socket
		this.serverSocket.Shutdown(SocketShutdown.Both);
		this.serverSocket.Close();
	}
	//loop request
}

Step Three: Define RequestHandler Functions

public string GetHeader(Socket socket)
{
	string header = "";
	while (true)
	{
		byte[] bytes = new byte[1];
		int bytesRec = socket.Receive(bytes);
		header += System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec);
		if (header.IndexOf("\r\n\r\n") > -1 || header.IndexOf("\n\n") > -1)
		{
			break;
		}
	}
	return header;
}
public void AnalyzeHeader(string header)
{
	string host;
	string[] headers = header.Split(new char[] { '\n' });
	string[] requestLineElements = requestLine.Split(new char[] {' '});

	for (int i = 1; i < headers.Length; ++i) {
                string[] hElem = headers[i].Split(new char[] { ':' });
                if (hElem.Length >= 2)
		{
			if (hElem[0].Trim().ToLower().Equals("host"))
			{
				host = hElem[1].Trim();
			}
		}
	}
	return host;
}
public void SendRequest(Socket socket, string header)
{
	byte[] bytesSent = System.Text.Encoding.ASCII.GetBytes(header);
	socket.Send(bytesSent, bytesSent.Length, SocketFlags.None);
}
Advertisements

6 Comments

  1. I wanna to learn this code for my network course would you please explain me in details how to run this codes in visual studio 2008 and some explanation about classes and functions use in the program.
    regards

  2. This code has quite a few problems, will not compile. Some are trivial, some require more work to fix… Could you update the above code after making sure it actually compiles?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s