admin管理员组

文章数量:819740

http请求判断网络状态

// http 请求返回码==200 表明网络连接正常
int checkWithHttpRequest()
{//加载套接字库WORD wVersionRequested;WSADATA wsaData;int err;wVersionRequested = MAKEWORD( 1, 1 );    //初始化Socket动态连接库,请求1.1版本的winsocket库err = WSAStartup( wVersionRequested, &wsaData );if ( err != 0 )return 1;if ( LOBYTE( wsaData.wVersion ) != 1 ||   //判断请求的winsocket是不是1.1的版本HIBYTE( wsaData.wVersion ) != 1 ) {WSACleanup( );				return 1;					}char http[60] = "www.baidu.com";			//访问网页SOCKET sock = socket(AF_INET,SOCK_STREAM,0);//建立socketif (sock == INVALID_SOCKET){return 1;}sockaddr_in hostadd;hostent* host = gethostbyname(http);//取得主机的IP地址if(host==NULL){//cout<<"主机处于没有联网状态;"<<endl;return -1;}//cout<<"主机处于联网状态,现在可以进行通信!"<<endl;memcpy(&hostadd,host->h_addr,sizeof(hostadd));//将返回的IP信息Copy到地址结构hostadd.sin_family = AF_INET;hostadd.sin_port = htons(80);char buf[1024]="GET / HTTP/1.1\r\nHost: ";//构造Http请求数据包strcat(buf,inet_ntoa(hostadd.sin_addr));strcat(buf," \r\nContent-Length: 10\r\n\r\n");strcat(buf,"Connection:close");int time = 1000;	//超时时间setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(char*)&time,sizeof(time));if (connect(sock,(sockaddr*)&hostadd,sizeof(hostadd)) == SOCKET_ERROR)//连接请求{//cout<<"与网页建立连接失败!"<<endl;return 1;}if (SOCKET_ERROR == send(sock,buf,strlen(buf)+1,0))//发送构造好的Http请求包{//cout<<"发送数据包失败!"<<endl;return 1;}memset(buf,0,1024);recv(sock,buf,1024,0);				//接收返回的数据//cout<<"从网页中获取的数据为:"<<buf;// 读取返回的html 第9-11个字节char testBuf[10] ;memset(testBuf, 0, 10);memcpy(testBuf, buf+9, 3);if(strcmp(testBuf, "200"))return 1;closesocket(sock);WSACleanup();return 0;
}



根据最后的 返回码,如果http请求返回200 表示连接正常


网络连接正常 返回 0

在第9-11字节


程序是借鉴 csdn  Jpday博主 的。

特此声明:

://blog.csdn.net/jpday/article/details/9329185




本文标签: http请求判断网络状态