2

我使用 SOL_SOCKET 协议编写了​​一个代码,但收到错误为 10043(套接字错误)。

代码如下:

#include <QCoreApplication>
#include<QDebug>
//#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>

/****************************************/
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
/****************************************/

#define DEFAULT_BUFLEN 512

int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN];

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    WSADATA wsaData;
    int iResult;
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    ZeroMemory( &hints, sizeof(hints) );
    //hints.ai_family = AF_UNSPEC;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = SOL_SOCKET;
    //hints.ai_protocol = IPPROTO_TCP;

#define DEFAULT_PORT "10990"

// 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;
}

SOCKET ConnectSocket = INVALID_SOCKET;

// Attempt to connect to the first address returned by
// the call to getaddrinfo
ptr=result;

// Create a SOCKET for connecting to 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;
}

    int rcvbuf = 8192;  /* recv buffer size */
    int z = setsockopt(ConnectSocket,SOL_SOCKET,SO_RCVBUF,
    (char*)&rcvbuf,sizeof(rcvbuf));

    do {
            iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
            if (iResult > 0)
            printf("Bytes received: %d\n", iResult);
            else if (iResult == 0)
            printf("Connection closed\n");
            else
            printf("recv failed: %d\n", WSAGetLastError());
       } while (iResult > 0);

    return a.exec();
}

当我运行它显示::

Error in socket:10043

我用谷歌搜索,发现错误是由于套接字类型的协议错误,我试图找到正确的协议和套接字类型匹配但找不到。我尝试了所有可能的套接字选项和协议匹配。任何身体都面临同样的问题?

4

1 回答 1

2

您在ai_protocol字段中输入了错误的值。它必须是IPPROTO_常量之一(例如IPPROTO_TCPIPPROTO_ICMP)。

SOL_SOCKET用于设置套接字选项(就像您稍后在代码中所做的那样)。

您通常不应设置该成员,除非设置为零。

于 2013-08-07T12:24:27.590 回答