开始学TCP/IP才发现以前C和c++学的有多肤浅
接下来就准备返璞归真啦 哈哈 转战c++ing...
1.了解基本Socket函数
SOCKET s = socket(family,type,protocal);
int nRet = connect(s,(sockaddr*)&sin,sizeof(s));
(sockaddr_in sin = {AF_INET;htons(80);inet_addr("210.34.32.2");})
send(socket,buffer,msglen,flags);
recv(socket,buffer,length,flags);
使用过程 http://blog.chinaunix.net/u/31179/showart_1101085.html
2.Http // GET,POST 发包
例:
char buffSend[] = "GET / HTTP/1.1/nHOST:www.hnu.cn/nconnection:close/n/n";
http://hi.baidu.com/bevan_007/blog/item/d9f000ed6176a44578f0554d.html
2009-11-24
昨天没来得及把代码附上,在此补充下:
#include <WinSock2.h>
#include <atlsocket.h>
#include <iostream>
using namespace std;
int main()
{
WORD wVersionRequested;
WSADATA wsadata;
int err;
//
wVersionRequested = MAKEWORD(1,1);
err = WSAStartup(wVersionRequested,&wsadata);
if (err == 0)
{
cout<<"WSAStartup() success."<<endl;
}else if (err == -1)
{
cout<<"WSAStartup() failed."<<endl;
}
//创建sockaddr_in
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
sin.sin_addr.S_un.S_addr = inet_addr("205.178.145.65");
SOCKET s = socket(PF_INET,SOCK_STREAM,0);
//将sockaddr_in转换成sockaddr后连接
int nRet = connect(s,(sockaddr*)&sin,sizeof(sin));
if(nRet == 0)
{
cout<<"Connect() success."<<endl;
}
else if(nRet == -1)
{
cout<<"Connect() failed."<<endl;
}
char buffSend[] = "GET / HTTP/1.1/nHOST:www.hnu.cn/nconnection:close/n/n";
send(s,buffSend,strlen(buffSend),0);
char buffRecv[1024] = {'/0'};
int len = recv(s,buffRecv,_countof(buffRecv),0);
if (len)
{
int i =0;
while(buffRecv[i] != '/0')
{
cout<<buffRecv[i];
i++;
}
cout<<endl<<i<<endl;
}
closesocket(s);
system("pause");
return 0;
}
实验过,可以通过。