我开始制作 C++ 服务器,但无法绑定到套接字。
#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 _tmain(int argc, _TCHAR* argv[])
{
connect("127.0.0.1", 500);
}
但是每次我尝试绑定时,我都会得到以下输出:
绑定到套接字时出错:错误:没有错误
但是套接字没有绑定。我究竟做错了什么?
已修复,必须使用 WSAStartup。