为什么包含“ boost / multiprecision / cpp_int.hpp”会破坏套接字?

时间:2019-04-29 16:38:03

标签: c++ boost winsock2

我有服务器应用程序的工作代码。 现在,我需要在项目中使用cpp_int。 但是,当我尝试包含 boost / multiprecision / cpp_int.hpp

  

accept(listeningSocket,(sockaddr *)&client,&sizeofclient);

返回 INVALID_SOCKET ,并且programm以代码3终止。

这是server.cpp的代码

#include <iostream>
#include <Ws2tcpip.h>
//#include <boost/multiprecision/cpp_int.hpp> // reason of the probmlem
#pragma comment(lib, "ws2_32.lib")
constexpr auto MSIZE = 4096;
using namespace std;

int main()
{
    WSADATA wsData;
    WORD ver = MAKEWORD(2, 2);
    if (WSAStartup(ver, &wsData) != 0)
    {
        cerr << "Can't initialise winsock\nQuiting...\n";
        return 1;
    }   
    SOCKET listeningSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (listeningSocket == INVALID_SOCKET)
    {
        cerr << "Can't create a socket!\nQuiting...\n";
        return 2;
    }
    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(54000);
    hint.sin_addr.S_un.S_addr = INADDR_ANY;
    bind(listeningSocket, (sockaddr*)&hint, sizeof(hint));
    listen(listeningSocket, SOMAXCONN);
    cout << "Listenning\n";
    sockaddr_in client;
    int sizeofclient = sizeof(client);
    SOCKET clientSocket = accept(listeningSocket, (sockaddr*)&client, &sizeofclient);
    if (clientSocket == INVALID_SOCKET)
    {
        cerr << "Invalid socket.\nQuiting...\n";
        return 3;
    }

    char host[NI_MAXHOST];
    char service[NI_MAXHOST];
    ZeroMemory(host, NI_MAXHOST);
    ZeroMemory(service, NI_MAXHOST);
    char buf[MSIZE];
    while (1)
    {
        ZeroMemory(buf, MSIZE);
        int bytesReceived = recv(clientSocket, buf, MSIZE, 0);
        if (bytesReceived == SOCKET_ERROR)
        {
            cerr << "Error in recv()\n";
            break;
        }
        if (bytesReceived == 0)
        {
            cout << "Client disconnected" << endl;
            break;
        }
        if (strcmp("\r\n", buf) != 0)
        {
            cout << "(Request from " << host << ") >>  " << buf << endl;
            if (strcmp(buf, "hello") == 0)
            {
                char response[100] = "Greetings!\n\r";
                send(clientSocket, response, sizeof(response) + 1, 0);
            }
            else 
            {
                char response[100] = "Invalid command!\n\r";
                send(clientSocket, response, sizeof(response) + 1, 0);
            }
        }
    }
    cout << "Quiting program\n";
    return 0;
}

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

问题是您使用using namespace std;的副作用。

当包含<boost/multiprecision/cpp_int.hpp>时,它会从C ++的<functional>头中提取std::bind(),这就是您的代码最终调用的函数,而不是Winsock的bind()函数。因此,listen()accept()失败,因为服务器套接字未绑定到网络接口(并且您的代码未检查bind()listen()上的错误)。如果您检查了listen()accept()的错误代码,您会发现它们都在报告WSAEINVAL(这意味着“套接字尚未与bind绑定”和“监听功能”没有在接受之前被调用”。

您需要

  • Get rid of using namespace std;,然后在需要的地方显式使用std::前缀(这是首选解决方案!)

  • 在调用bind()时,可以在其前面加上::,以告知编译器您要从全局名称空间(Win32 API,例如Winsock ,请勿在C ++中使用名称空间),而不要使用bind()名称空间中的名称空间。