How to avoid crash?

This function of code cause my program crash if there is no internet connection. Is it possible to avoid that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
void get_Website(string url) {
	WSADATA wsaData;
	SOCKET Socket;
	SOCKADDR_IN SockAddr;
	int lineCount = 0;
	int rowCount = 0;
	struct hostent *host;
	string get_http;


	get_http = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
		cout << "WSAStartup failed.\n";
		//system("pause");
		return ;
	}

	Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	host = gethostbyname(url.c_str());

	SockAddr.sin_port = htons(80);
	SockAddr.sin_family = AF_INET;
	SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);

	if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0) {
		cout << "Could not connect";
		//system("pause");
		return;
	}
	send(Socket, get_http.c_str(), strlen(get_http.c_str()), 0);

	int nDataLength;
	while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
		int i = 0;
		while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {

			website_HTML += buffer[i];
			i += 1;
		}
	}

	closesocket(Socket);
	WSACleanup();

}
Last edited on
I don't know exactly which part causes the crash, but I assume you'd be familiar with it. You should use a try/catch blocks. I assume some kind of exception is thrown when it fails to connect. Put the code you think presents the issue in the "try" block. Then put what you want to do when the issue comes up in the "catch" block. This way, when it throws an exception, you can handle it rather than crash.

1
2
3
4
5
6
7
8
9
10
11
int main() 
{
	try 
	{

	}
	catch (...)
	{
		
	}
}
It's probably this line:
host = gethostbyname(url.c_str());
gethostbyname returns null if resolution fails, which is something that will usually happen if you don't have an internet connection.

-Albatross
Blindly plowing on without checking if you received a valid host name is not a good idea.

https://docs.microsoft.com/en-us/windows/win32/api/wsipv6ok/nf-wsipv6ok-gethostbyname
Thanks! I use different function now. This is my solution.
LOL
I use different function now.

Will you check for an error status with this new function should it fail? Or ignore errors as you did with the previous function?

The problem wasn't a bad function, it was not checking if the function failed and continuing on as if you had valid data to work with.
Registered users can post here. Sign in or register to post.