socket()套接字创建失败

Input::Input(uint16_t port, uint16_t gpsPort)
{
  socketForLidar = -1;//00
  socketForLidar = socket(PF_INET, SOCK_DGRAM, 0);
  //if (socketForLidar == -1)//00
  if (INVALID_SOCKET == socketForLidar)
  {
    perror("socket"); // TODO: perror errno
    return;
  }
  ...
  ...
}

运行发现程序进入了if (INVALID_SOCKET == socketForLidar)----即socket()创建套接字失败!
后来想到之前学mfc网络编程最一开始是要加载套接字库,设置套接字版本信息等:
于是添加如下信息:

Input::Input(uint16_t port, uint16_t gpsPort)
{
//首先加载套接字库信息
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    wVersionRequested = MAKEWORD(2, 1); //高位字节存储副版本号, 低位字节存储主版本号
    err = WSAStartup(wVersionRequested, &wsaData);//WSAStartup,即WSA(Windows Sockets Asynchronous,Windows异步套接字)的启动命令
    if (err != 0)
    {
        return;
    }

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 1)//高位字节和低位字节不正确
    {
        WSACleanup();
        return;
    }
  
  socketForLidar = -1;//00
  socketForLidar = socket(PF_INET, SOCK_DGRAM, 0);

  //if (socketForLidar == -1)//00
  if (INVALID_SOCKET == socketForLidar)
  {
    perror("socket"); // TODO: perror errno
    return;
  }
  ......
  ......
}

综上:socket()返回INVALID_SOCKET,一般是在程序运行前没有执行WSAStartup()操作!Winsock未初始化或初始化失败!socket()套接字创建失败_第1张图片

你可能感兴趣的:(socket()套接字创建失败)