调用connect()时程序崩溃

时间:2016-01-18 06:42:22

标签: c++ winapi networking

我投入了一些打印语句,发现我的程序在调用connect()时崩溃了。我做了一些谷歌搜索并查看了代码并且不确定发生了什么,我在连接调用之前调用GetLastError()并且没有任何问题,程序中没有任何错误然后整个事情立即崩溃。 它显然甚至没有尝试连接到服务器,因为它已经崩溃,所以不会打印出任何东西 所以,我不知道这里发生了什么,并且我的常用方法都不会起作用,因为程序在没有输出任何输出的情况下崩溃,并且没有任何操作可能会出错。

WSAData wsaData;

int iResult;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {

#ifdef debug    
    printf("WSAStartup failed: %d\n", iResult);
#endif

    return 1;
}

struct addrinfo *result = NULL,
    *ptr = NULL,
    hints;

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

#define DEFAULT_PORT "80"

std::string www = "tildetictac.x10host.com";
// Resolve the server address and port
iResult = getaddrinfo(www.c_str(), DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
#ifdef debug
    printf("getaddrinfo failed: %d\n%d\n", iResult, GetLastError());
#endif
    WSACleanup();
    return 1;
}
else {
#ifdef debug
    std::cout << "success \n";
#endif
}

SOCKET connectSocket = INVALID_SOCKET;

printf("error: %d", GetLastError());

// Connect to server.
iResult = connect(connectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
std::cout << "2"; 
// this doesn't get printed before the crash, so its for sure connect()

1 个答案:

答案 0 :(得分:0)

您必须将result分配给ptr。否则,您将取消引用NULL指针,这将导致崩溃。

    std::string www = "tildetictac.x10host.com";
    // Resolve the server address and port
    iResult = getaddrinfo(www.c_str(), DEFAULT_PORT, &hints, &result);
    if (iResult != 0) {
    #ifdef debug
        printf("getaddrinfo failed: %d\n%d\n", iResult, GetLastError());
    #endif
        WSACleanup();
        return 1;
    }
    else {
    #ifdef debug
        std::cout << "success \n";
    #endif
    }

    ptr = result; //ADDED

    // Create a SOCKET for connecting to server
    connectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
    if (connectSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

请看一下这个例子:

Complete Winsock Client Code