C++ determines whether the host is in network state

  • 2020-06-07 04:51:36
  • OfStack

The example of this paper shares the specific code of C++ to determine whether the host is in the state of networking for your reference, the specific content is as follows

Let the machine directly access to a website, if successful, it means that the successful networking, no access to the success, then no networking!!


#include<iostream>
#include <WINSOCK2.H>
#pragma comment(lib,"ws2_32.lib")
#define LEN 1024 // The size of the received data 
using namespace std;
 
 
int main()
{
 // Load the socket library 
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 
 wVersionRequested = MAKEWORD( 1, 1 );  // Initialize the Socket Dynamic connection library , request 1.1 Version of the winsocket library 
 
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
 return 0;
 }
 
 if ( LOBYTE( wsaData.wVersion ) != 1 ||  // Judging the request winsocket Isn't it 1.1 The version of the 
    HIBYTE( wsaData.wVersion ) != 1 ) {
 WSACleanup( );  // liquidation 
 return 0;   // Termination of winsocket use 
 }
 //WSADATA ws;
 //WSAStartup(MAKEWORD(2,2),&ws);//
 char http[60] = "www.google.com";  // Visit the Google page 
 SOCKET sock = socket(AF_INET,SOCK_STREAM,0);// To establish socket
 if (sock == INVALID_SOCKET)
 {
 cout<<" Set up access socket The socket failed !"<<endl;
 return 0;
 }
 sockaddr_in hostadd;
 hostent* host = gethostbyname(http);// Acquired host IP address 
 if(host==NULL)
 {
 cout<<" The host is not connected ;"<<endl;
 return 0;
 }
 cout<<" The host is networked and can now communicate !"<<endl;
 memcpy(&hostadd,host->h_addr,sizeof(hostadd));// Returns the IP information Copy To address structure 
 hostadd.sin_family = AF_INET;
 hostadd.sin_port = htons(80);
 
 
 char buf[LEN]="GET / HTTP/1.1\r\nHost: ";// structure Http Request packet 
 strcat(buf,inet_ntoa(hostadd.sin_addr));
 strcat(buf," \r\nContent-Length: 10\r\n\r\n");
 strcat(buf,"Connection:close");
 
 
 int time = 1000; // timeout 
 setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(char*)&time,sizeof(time));
 
 
 if (connect(sock,(sockaddr*)&hostadd,sizeof(hostadd)) == SOCKET_ERROR)// Connection request 
 {
 cout<<" Failed to establish connection with web page !"<<endl;
 return 0;
 }
 if (SOCKET_ERROR == send(sock,buf,strlen(buf)+1,0))// Transmit constructed Http Request packet 
 {
 cout<<" Sending packet failed !"<<endl;
 return 0;
 }
 memset(buf,0,LEN);
 recv(sock,buf,LEN,0);  // Receive the returned data 
 cout<<" The data obtained from the webpage is :"<<buf;
 closesocket(sock);
 WSACleanup();
return 0;
}

Related articles: