移植到 windows 个套接字

Porting to windows sockets

我正在尝试移植一些遗留代码并发现了一些问题。

我已经分离出一个简单示例的代码。下面的套接字创建代码有什么问题?

#include <iostream>
#include <winsock2.h>

int main()
{
    std::cout << "Hello World!\n";
    sockaddr_in sockAddr;
    uint16_t PortNumber = 2000;
    memset(&sockAddr, 0, sizeof(sockAddr));
    sockAddr.sin_family = AF_INET;
    sockAddr.sin_port = htons(PortNumber);
    sockAddr.sin_addr.s_addr = 0;
    auto result = socket(AF_INET, SOCK_STREAM, 0);

    if (result == INVALID_SOCKET)
    {
        auto err = WSAGetLastError();
        std::cout << "Unable to create listening socket on port " << PortNumber << "with error "  << err;
    }
    else std::cout << "No socket error \n";
}

您需要先初始化它,然后再进行任何套接字调用。

int iResult; 
// Initialize Winsock 
iResult = WSAStartup(MAKEWORD(2,2), &wsaData); 
if (iResult != 0) 
{ 
   printf("WSAStartup failed: %d\n", iResult); 
   return 1; 
}