代码如下(摘自:http://bbs.csdn.net/topics/320012075):
#include <winsock2.h> #include<windows.h> #include<stdio.h> #pragma comment(lib, "ws2_32.lib") int main(int argc, char* argv[]) { char server_name[256]= "www.163.com"; WSADATA wsaData; struct sockaddr_in srv_addr; if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR) { WSACleanup(); return -1; } SOCKET cli_sock=socket(PF_INET,SOCK_STREAM,0); if (cli_sock==INVALID_SOCKET) return -1; // connect to server srv_addr.sin_family = AF_INET; LPHOSTENT lphost = gethostbyname(server_name); if (lphost != NULL) srv_addr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr; srv_addr.sin_port= ntohs(80); if (connect(cli_sock,(LPSOCKADDR)&srv_addr,sizeof(srv_addr))==SOCKET_ERROR){ return -1; } char sz[]="GET / HTTP/1.1\r\nHost:www.163.com\r\n\r\n"; int retval = send(cli_sock,sz,sizeof(sz)-1,0); if( SOCKET_ERROR == retval ) return 0; char buffer[1024]={0}; while( SOCKET_ERROR != retval ){ retval = recv(cli_sock ,buffer,1000,0); printf("%s\n",buffer); } closesocket(cli_sock); return 0; }VC6下运行可用。
对于http get请求报文格式说明。
如将下面的URL转化成GET请求报文:
http://192.168.11.240/[email protected]
转换为:
GET(space)/[email protected](space)HTTP/1.1(\r\n)
Host:192.168.11.240(\r\n)
Accept:*/*(\r\n)
User-Agent:MSIE 6.00(\r\n)
Connection:Keep-Alive(\r\n)