Introduction
Many people have been asking me about a how to create a proxy. Actually is very
simple to do in Managed C++. This article is made very simple, you can add as
much as you want at the base class we can call it CHttpProxy
I'll be using the known class TcpClient.
__gc class CHttpProxy
{
public:
CHttpProxy(String __gc *szHost, int port);
String __gc *m_host;
int m_port;
unsigned char SendToServer(unsigned char Packet __gc[]) __gc[];
};
#using <mscorlib.dll>
#using <SYSTEM.DLL>
using namespace System;
using System::Net::Sockets::TcpClient;
using System::String;
using System::Exception;
using System::Net::Sockets::NetworkStream;
#include "httpproxy.h"
#include <stdio.h>
CHttpProxy::CHttpProxy(String __gc *szHost, int port)
{
m_host = szHost;
m_port = port;
}
unsigned char CHttpProxy::SendToServer(unsigned char Packet __gc[]) __gc[]
{
TcpClient * tcpclnt = new TcpClient();
unsigned char bytes __gc[];
try
{
tcpclnt->Connect(m_host,m_port);
}
catch (Exception * e )
{
Console::WriteLine(e->ToString());
return NULL;
}
if ( tcpclnt )
{
NetworkStream * networkStream = tcpclnt->GetStream();
int size = Packet->get_Length();
networkStream->Write(Packet, 0, size);
bytes = new unsigned char __gc[tcpclnt->ReceiveBufferSize];
networkStream->Read(bytes, 0, (int) tcpclnt->ReceiveBufferSize);
return (bytes);
}
return (NULL);
}
Simple isn't it? This class creates a connection to the "real" IIS server.
So(...) How to use it now? Simpler than bowling water, you may remember this
part of the code from my previous article:
TcpListener * pTcpListener;
TcpListener = new TcpListener(80);
TcpListener->Start();
TcpClient * pTcpClient;
unsigned char sendbytes __gc[];
pTcpClient = m_TcpListener->AcceptTcpClient();
NetworkStream * networkStream = pTcpClient->GetStream();
bytes = new unsigned char __gc[tcpCl->ReceiveBufferSize];
networkStream->Read(bytes, 0, (int) tcpCl->ReceiveBufferSize);
Console::WriteLine(S"Packet Received");
CHttpProxy *pProxy;
pProxy = new CHttpProxy(S"www.codeproject.com", 80);
sendbytes = pProxy->SendToServer(bytes);
networkStream->Write(sendbytes, 0 , sendbytes->get_Length());
networkStream->Close();
We listen on port 80 for any connection. Anything that comes in that port is
re-directed to www.codeproject.com It's
actually a pretty easy concept. The most interesting part comes when you get
the buffer. You got the control to remove images from the HTML or change the
content on the fly.
In my next article will look into those possibilities.