为什么getsockopt会返回错误?

时间:2017-09-01 12:32:03

标签: c windows sockets

我在Windows上遇到套接字问题。调用getsockopt()总是失败。奇怪的是,setsockopt()似乎工作(至少它报告成功......虽然我设置的选项似乎没有我期望的效果)。

我的代码如下。运行它会报告成功的setsockopt调用,但getsockopt会因WSAEFAULT而失败。我做错了什么?

        struct linger ling;

        ...

        ling.l_onoff = 1;
        ling.l_linger = 10;
        if (setsockopt(sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) == SOCKET_ERROR) {
            fprintf(stderr, "******** setsockopt failed\n");
            ret = -1;
            break;
        } else {
            fprintf(stderr, "******** setsockopt success\n");
        }
        if (getsockopt(sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) == SOCKET_ERROR) {
            fprintf(stderr, "****** failed getting sockopt\n");
            switch(WSAGetLastError()) {
                case WSANOTINITIALISED:
                    fprintf(stderr, "******WSANOTINITIALISED\n");
                    break;
                case WSAENETDOWN:
                    fprintf(stderr, "******WSAENETDOWN\n");
                    break;
                case WSAEFAULT:
                    fprintf(stderr, "******WSAEFAULT\n");
                    break;
                case WSAEINPROGRESS:
                    fprintf(stderr, "******WSAEINPROGRESS\n");
                    break;
                case WSAEINVAL:
                    fprintf(stderr, "******WSAEINVAL\n");
                    break;
                case WSAENOPROTOOPT:
                    fprintf(stderr, "******WSAENOPROTOOPT\n");
                    break;
                case WSAENOTSOCK:
                    fprintf(stderr, "******WSAENOTSOCK\n");
                    break;
                default:
                    fprintf(stderr, "******Unknown error %d\n", ret);
                    break;
            }
        }

1 个答案:

答案 0 :(得分:4)

getsockopt的最后一个参数是指针,而不是size_t。

documentation注意getsockopt被声明为:

int getsockopt(
  _In_    SOCKET s,
  _In_    int    level,
  _In_    int    optname,
  _Out_   char   *optval,
  _Inout_ int    *optlen
);

您需要初始化大小为optval的int,并将指向该int的指针作为最后一个参数传递。将您的代码更改为:

int slen;
..
slen = sizeof ling;
getsockopt(sock, SOL_SOCKET, SO_LINGER, &ling, &slen)