调用 connect() 时程序崩溃

Program Crashes when making call to connect()

本文关键字:程序 崩溃 connect 调用      更新时间:2023-10-16

我扔了一些打印语句,发现我的程序在调用connect()时崩溃了。 我做了一些谷歌搜索并查看了代码,不确定发生了什么,我在连接呼叫之前打电话给GetLastError(),没有任何问题,程序中没有任何问题,然后整个事情立即崩溃。很明显,它甚至没有尝试连接到服务器,并且由于崩溃而无法打印出任何内容。
所以,我不知道这里发生了什么,我常用的方法都不起作用,因为程序在没有输出任何输出的情况下崩溃,并且没有任何问题。

WSAData wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
#ifdef debug    
    printf("WSAStartup failed: %dn", 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: %dn%dn", 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()

您必须将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: %dn%dn", 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: %ldn", WSAGetLastError());
        WSACleanup();
        return 1;
    }

请看这个例子:

完整的 Winsock 客户端代码