Windows上的socket选项TCP_NODELAY需要8bit Bool?

时间:2017-11-13 14:58:47

标签: c sockets visual-studio-2010 winsock2 getsockopt

这是我的示例代码(很抱歉很长):

#include "stdafx.h"
#ifndef WIN32_LEAN_AND_MEAN
  #define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>

typedef BOOL OPT_TYPE;

int _tmain(int argc, _TCHAR* argv[])
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2,2), &wsaData);

    int handle= socket(AF_INET, SOCK_STREAM, 0);
    if(SOCKET_ERROR == handle )
    {
      int error =  WSAGetLastError();
      printf("ERROR in socket: errno: %d\n", error);
      return error;
    }

   OPT_TYPE flag = -1;
   int flagLength = sizeof(flag);
   if (SOCKET_ERROR == getsockopt(handle, IPPROTO_TCP, TCP_NODELAY,
         reinterpret_cast<char*>(&flag), &flagLength))
   {
      int error =  WSAGetLastError();
      printf("ERROR in getsockopt: errno: %d\n", error);
      return error;
   }
   if(TRUE != flag && FALSE != flag)
   {
      printf("ERROR in getsockopt (default value): flag is invalid: %d, length is %d\n", flag, flagLength);
   }

   OPT_TYPE setflag = TRUE;
   if (SOCKET_ERROR == setsockopt(handle, IPPROTO_TCP, TCP_NODELAY,
         reinterpret_cast<char*>(&setflag), flagLength))
   {
      int error =  WSAGetLastError();
      printf("ERROR in getsockopt: errno: %d\n", error);
      return error;
   }
   if (SOCKET_ERROR == getsockopt(handle, IPPROTO_TCP, TCP_NODELAY,
         reinterpret_cast<char*>(&flag), &flagLength))
   {
      int error =  WSAGetLastError();
      printf("ERROR in getsockopt: errno: %d\n", error);
      return error;
   }
   if(TRUE != flag && FALSE != flag)
   {
      printf("ERROR in getsockopt (default value): flag is invalid: %d, length is %d\n", flag, flagLength);
   }

   setflag = FALSE;
   if (SOCKET_ERROR == setsockopt(handle, IPPROTO_TCP, TCP_NODELAY,
         reinterpret_cast<char*>(&setflag), flagLength))
   {
      int error =  WSAGetLastError();
      printf("ERROR in getsockopt: errno: %d\n", error);
      return error;
   }
   if (SOCKET_ERROR == getsockopt(handle, IPPROTO_TCP, TCP_NODELAY,
         reinterpret_cast<char*>(&flag), &flagLength))
   {
      int error =  WSAGetLastError();
      printf("ERROR in getsockopt: errno: %d\n", error);
      return error;
   }
   if(TRUE != flag && FALSE != flag)
   {
      printf("ERROR in getsockopt (default value): flag is invalid: %d, length is %d\n", flag, flagLength);
   }
   return 0;
}

打印:

ERROR in getsockopt (default value): flag is invalid: -256, length is 1
ERROR in getsockopt (default value): flag is invalid: -255, length is 1
ERROR in getsockopt (default value): flag is invalid: -256, length is 1

有人可以重现吗? 注意:我在Win7上,x64使用VS2010编译x32应用程序。

getsockopt上的文档说我应该使用BOOLIPPROTO_TCP上的文档说我应该使用DWORD。但两者都不起作用。将OPT_TYPE设置为8位类型(例如char)时,它可以正常工作。我错过了文档中的内容吗?

0 个答案:

没有答案