winsock connect方法的错误10038

时间:2014-04-14 21:18:30

标签: c++ winsock wsastartup

我正在尝试与在与客户端在同一台计算机上运行的服务器应用程序建立简单连接。

我的代码如下所示:

void Base::Connect(string ip, string port)
{
    int status;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo hints;
    struct addrinfo *servinfo;  // will point to the results

    memset(&hints, 0, sizeof hints); // make sure the struct is empty
    hints.ai_family = AF_UNSPEC;     // don't care IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM; // TCP stream sockets

    // get ready to connect
    status = getaddrinfo(ip.c_str(), port.c_str(), &hints, &servinfo);

    // Socket Setup
    if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
    {
        printf("[NETWORKING] An error occured when setting up socket\n");
    }

    // Connect
    if (connect(ConnectSocket, servinfo->ai_addr, (int)servinfo->ai_addrlen) == SOCKET_ERROR)
    {
        int error = WSAGetLastError();
        printf("Connect error: ", error);
    }
}

事先,我打电话给WSAStartup()并且它不会抛出任何错误。如果服务器开启或关闭,则错误不会改变。

我使用的IP是127.0.0.1,我通过端口80连接。我尝试了其他的东西(1337)给了我同样的错误。

有什么明显的错误吗?关于可能出现什么问题的任何想法?

1 个答案:

答案 0 :(得分:2)

if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)

你将socket(...)与INVALID_SOCKET进行比较 然后你将结果true / false分配给ConnectSocket 使用

if ((ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == INVALID_SOCKET)

参见C ++运算符优先级列表