当前位置: 首页 > 知识库问答 >
问题:

Winsock:使用localhost(127.0.0.1)时连接失败,错误为10049

韦飞尘
2023-03-14
    null
  1. 创建套接字->将其绑定到随机端口
  2. 呼叫连接:连接到本地主机,端口12345

=>连接调用失败,错误为10049,如上所述

这里是包括“服务器”在内的主要功能:

HANDLE hThread = NULL;
Inc::CSocketTCP ServerSock;
Inc::CSocketTCP ClientSock;

try
{

    ServerSock.Bind(L"", L"12345");
    ServerSock.Listen(10);

    //Spawn the senders-thread
    hThread = (HANDLE)_beginthreadex(nullptr, 0, Procy, nullptr, 0, nullptr);

    //accept
    ServerSock.Accept(ClientSock);


    //Adjust the maximum packet size
    ClientSock.SetPacketSize(100);


    //receive data
    std::wstring Data;
    ClientSock.Receive(Data);

    std::wcout << "Received:\t" << Data << std::endl;
}
catch(std::exception& e)
{...
unsigned int WINAPI Procy(void* p)
Sleep(1500);
try{
    Inc::CSocketTCP SenderSock;
    SenderSock.Bind(L"", L"123456");

    SenderSock.Connect(L"localhost", L"12345");


    //Adjust packet size
    SenderSock.SetPacketSize(100);

    //Send Data
    std::wstring Data = L"Hello Bello!";
    SenderSock.Send(Data);
}
catch(std::exception& e)
{
    std::wcout << e.what() << std::endl;
}...
    int Inc::CSocketTCP::Connect(const std::wstring& IP, const std::wstring& Port)
{
    //NOTE: assert that the socket is valid
    assert(m_Socket != INVALID_SOCKET);

    //for debuggin: convert WStringToString here
    std::string strIP = WStringToString(IP), strPort = WStringToString(Port);

    Incgetaddrinfo AddyResolver;
    addrinfo hints = {}, *pFinal = nullptr;

    hints.ai_family = AF_INET;

    //resolve the ip/port-combination for the connection process
    INT Ret = AddyResolver(strIP.c_str(), strPort.c_str(), &hints, &pFinal);
    if(Ret)
    {
        //error handling: throw an error description
        std::string ErrorString("Resolving Process failed (Connect): ");
        ErrorString.append(Inc::NumberToString<INT>(Ret));
        throw(std::runtime_error(ErrorString.c_str()));
    }


    /*---for debbuging---*/
    sockaddr_in *pP = (sockaddr_in*)(pFinal->ai_addr);
    u_short Porty = ntohs(pP->sin_port);
    char AddBuffer[20] = "";

    InetNtopA(AF_INET, (PVOID)&pP->sin_addr, AddBuffer, 20);
    /*--------------------------------------------------------*/


    if(connect(m_Socket, pFinal->ai_addr, pFinal->ai_addrlen) == SOCKET_ERROR)
    {
        int ErrorCode = WSAGetLastError();
        if((ErrorCode == WSAETIMEDOUT) || (ErrorCode == WSAEHOSTUNREACH) || (ErrorCode == WSAENETUNREACH))
        {
            //Just Unreachable
            return TCP_TARGETUNREACHABLE;
        }

        //real errors now
        std::string ErrorString("Connection Process failed: ");
        ErrorString.append(Inc::NumberToString<int>(ErrorCode));
        throw(std::runtime_error(ErrorString.c_str()));
    }

    return TCP_SUCCESS;
}

共有1个答案

罗淮晨
2023-03-14

你的问题中有答案:

这意味着服务器绑定到接口的实际IP,而不是inaddr_any,即它不侦听环回。

在创建侦听套接字时,您并不真正需要名称解析。只需bind()将其绑定到inaddr_any以侦听所有可用接口(包括环回)。

 类似资料: