1 #include<iostream> 2 #include <WINSOCK2.H> 3 #pragma comment(lib,"ws2_32.lib") 4 #define LEN 1024 //接收数据的大小 5 using namespace std; 6 7 8 int main() 9 { 10 //加载套接字库 11 WORD wVersionRequested; 12 WSADATA wsaData; 13 int err; 14 15 wVersionRequested = MAKEWORD( 1, 1 ); //初始化Socket动态连接库,请求1.1版本的winsocket库 16 17 err = WSAStartup( wVersionRequested, &wsaData ); 18 if ( err != 0 ) { 19 return 0; 20 } 21 22 if ( LOBYTE( wsaData.wVersion ) != 1 || //判断请求的winsocket是不是1.1的版本 23 HIBYTE( wsaData.wVersion ) != 1 ) { 24 WSACleanup( ); //清盘 25 return 0; //终止对winsocket使用 26 } 27 //WSADATA ws; 28 //WSAStartup(MAKEWORD(2,2),&ws);// 29 char http[60] = "www.google.com"; //访问谷歌网页 30 SOCKET sock = socket(AF_INET,SOCK_STREAM,0);//建立socket 31 if (sock == INVALID_SOCKET) 32 { 33 cout<<"建立访问socket套接字失败!"<<endl; 34 return 0; 35 } 36 sockaddr_in hostadd; 37 hostent* host = gethostbyname(http);//取得主机的IP地址 38 if(host==NULL) 39 { 40 cout<<"主机处于没有联网状态;"<<endl; 41 return 0; 42 } 43 cout<<"主机处于联网状态,现在可以进行通信!"<<endl; 44 memcpy(&hostadd,host->h_addr,sizeof(hostadd));//将返回的IP信息Copy到地址结构 45 hostadd.sin_family = AF_INET; 46 hostadd.sin_port = htons(80); 47 48 49 char buf[LEN]="GET / HTTP/1.1\r\nHost: ";//构造Http请求数据包 50 strcat(buf,inet_ntoa(hostadd.sin_addr)); 51 strcat(buf," \r\nContent-Length: 10\r\n\r\n"); 52 strcat(buf,"Connection:close"); 53 54 55 int time = 1000; //超时时间 56 setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(char*)&time,sizeof(time)); 57 58 59 if (connect(sock,(sockaddr*)&hostadd,sizeof(hostadd)) == SOCKET_ERROR)//连接请求 60 { 61 cout<<"与网页建立连接失败!"<<endl; 62 return 0; 63 } 64 if (SOCKET_ERROR == send(sock,buf,strlen(buf)+1,0))//发送构造好的Http请求包 65 { 66 cout<<"发送数据包失败!"<<endl; 67 return 0; 68 } 69 memset(buf,0,LEN); 70 recv(sock,buf,LEN,0); //接收返回的数据 71 cout<<"从网页中获取的数据为:"<<buf; 72 closesocket(sock); 73 WSACleanup(); 74 return 0; 75 }
链接:https://blog.csdn.net/jpday/article/details/9329185