浅谈http代理服务器的穿透(2)
Author : Leen
思路就是先用套接字连接代理服务器,然后给代理服务器发送http请求,代理服务器向远程服务器转发请求
以下为一个通过HTTP代理服务器下载网页的小程序
主要代码如下:
void CMyGetHTTPFileDlg::OnBnClickedButtonGet()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(TRUE);
CString strIp ;
char szIp[32];
memset(szIp,0,32);
char szWebSite[128];
memset(szWebSite,0,128);
m_CtrlIpAddress.GetWindowText(strIp);
//Unicode 工程需要将宽字节转成多字节
WideCharToMultiByte(CP_ACP,0,strIp.GetBuffer(),-1,szIp,32,NULL,NULL);
WideCharToMultiByte(CP_ACP,0,m_StrWbeSite.GetBuffer(),-1,szWebSite,128,NULL,NULL);
m_local.sin_family=AF_INET;
m_local.sin_port=htons(m_iServerPort);
m_local.sin_addr.S_un.S_addr=inet_addr(szIp);
m_socket=socket(AF_INET,SOCK_STREAM,0);
int ret;
//联接代理服务器
ret=connect(m_socket,(LPSOCKADDR)&m_local,sizeof(m_local));
//有错的话
if(ret!=0)
{
int ierror = WSAGetLastError() ;
CString strerror ;
strerror.Format(_T("联接错误,错误代码:%d"),ierror);
AfxMessageBox( strerror );
closesocket(m_socket);
return ;// -1;
}
// AfxMessageBox( "连接服务器成功 ");
CFile m_file;
m_file.Open(_T("C:\\myhtml.htm"),CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
WORD wd = 0xfeff;
// m_file.Write(&wd,2);
char buff[1024];
//HTTP 1.1
sprintf(buff,"GET http://%s/ HTTP/1.1\
Host: %s\r\n\
Proxy-Connection: keep-alive\r\n\
User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1\r\n\
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n\
Accept-Language: zh-CN,zh;q=0.8\r\n\
Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n\r\n",szWebSite,szWebSite);
send(m_socket,buff,strlen(buff),0); //发送请求
memset(buff,0,1024);
recv(m_socket,buff,1024,0);
// recv(m_socket,buff,1024,0);
// recv(m_socket,buff,1024,0);
// recv(m_socket,buff,1024,0);
// recv(m_socket,buff,1024,0);
//返回代理的response消息
if(strstr(buff, "HTTP/1.")==NULL)
{
AfxMessageBox( _T("通过代理连接外网不成功! "));
closesocket(m_socket);
return ;// 0;
}
char* pchar = strstr(buff,"<html");
if(pchar != NULL)
m_file.Write(pchar,1024-(pchar - buff));
while(TRUE)
{
memset(buff,0,1024);
//接收完成后推出
if( 0 == recv(m_socket,buff,1024,0) )
break;
//去掉没用的字符,确保html脚本的正确
char* pchar = strstr(buff,"<html");
if(pchar != NULL)
m_file.Write(pchar,1024-(pchar - buff));
else
m_file.Write(buff,1024);
}
//关闭文件
m_file.Close();
}
程序比较简单,希望和大家多多交流!!!这篇文章我也贴在了 VC驿站
地址:http://www.cctry.com/thread-49887-1-1.html