Hey folks!
Here's the compilable code. The line in red is what causes the access violation.
Code:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#define STORAGE_LEN 1000
#define DEFAULT_PORT "80"
char storage[STORAGE_LEN];
SOCKET ConnectSocket = INVALID_SOCKET;
void write_to_file(char *storage)
{
FILE *p_openfile = fopen("c:\\programs\\networking\\webpagecontent.txt" , "a+");
fprintf(p_openfile, "%s\n", storage);
fclose(p_openfile);
}
int main(int argc, char **argv)
{
WSADATA wsaData;
int iResult;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
// Validate parameters
if(argc !=2) {
printf("usage: %s server-name\n", argv[0]);
return 1;
}
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if(iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
sprintf(storage, "WSAStartup = %d\n", iResult);
write_to_file(storage);
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
if(iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return 1;
}
sprintf(storage, "getaddrinfo = %d\n", iResult);
write_to_file(storage);
// Attempt to connect to an address until one succeeds
for(ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// Create a socket for connecting to the server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if(ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
}
sprintf(storage, "socket = %d\n", ConnectSocket);
write_to_file(storage);
// Connect to server
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if(iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}
freeaddrinfo(result);
if(ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to the server!\n");
return 1;
}
return 0;
}
I am still a bit too newbie to know what is the exact problem. Is it because ptr is NULL? Am I supposed to create another struct addrinfo object, and assign ptr to it?
If I was to write
before the line in red, a SOCKET ERROR is the result.
Thanks in advance.