WinSock2绑定错误

时间:2013-10-26 11:18:55

标签: c++ windows sockets winsock2

我开始制作C ++服务器,但我无法绑定到socket。

#pragma once

#include <WinSock2.h>
#include <thread>

#include "Logging.h"

namespace network
{
static SOCKET sock;

static VOID startAccept()
{
    while (true)
    {
        struct sockaddr_in serv_addr, cli_addr;
        int clilen = sizeof(cli_addr);

        SOCKET accepted;

        if (accepted == NULL)
        {
            accepted = accept(sock, (struct sockaddr *) &cli_addr, &clilen);

            if (accepted < 0)
            {
                core::writeln("Error accept: " + WSAGetLastError());
            }
            else
            {
                core::writeln("New connection from " + cli_addr.sin_addr.S_un.S_addr);
            }
        }
    }
}

static VOID connect(const char* ipAddress, u_short port)
{
    struct sockaddr_in serv_addr, cli_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(port);

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (sock < 0)
    {
        core::writeln("Error creating socket: " );
        perror("error:");
        return;
    }

    else if (bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
    {
        core::writeln("Error binding to socket: " );
        perror("error:");
        return;
    }

    else if (listen(sock, 10) < 0)
    {
        core::writeln("Error listening socket: ");
        return;
    }

    else
    {
        core::writeln("Bound WinSock to " + serv_addr.sin_addr.S_un.S_addr);

        std::thread accepting(startAccept);
        accepting.join();
    }
}
};

在我的主要int:

int _tmain(int argc, _TCHAR* argv[])
{
connect("127.0.0.1", 500);
}

但每次我尝试绑定时,都会得到以下输出:

绑定到套接字时出错: 错误:无错误

但套接字没有绑定。我做错了什么?


FIXED,必须使用WSAStartup。

0 个答案:

没有答案