我正在尝试与客户端应用在同一台计算机上运行的服务器应用建立简单连接。
我的代码是这样的:
void Base::Connect(string ip, string port)
{
int status;
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo hints;
struct addrinfo *servinfo; // will point to the results
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
// get ready to connect
status = getaddrinfo(ip.c_str(), port.c_str(), &hints, &servinfo);
// Socket Setup
if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
{
printf("[NETWORKING] An error occured when setting up socket\n");
}
// Connect
if (connect(ConnectSocket, servinfo->ai_addr, (int)servinfo->ai_addrlen) == SOCKET_ERROR)
{
int error = WSAGetLastError();
printf("Connect error: ", error);
}
}
之前,我调用了 WSAStartup()
,它没有抛出任何错误。如果服务器打开或关闭,错误不会改变。
我使用的 IP 是 127.0.0.1,我通过端口 80 进行连接。我尝试了其他方法 (1337),这给了我同样的错误。
有什么明显的错误吗?关于可能出现问题的任何想法?
最佳答案
if (ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol) == INVALID_SOCKET)
您正在将 socket(...) 与 INVALID_SOCKET
进行比较
然后您将结果 true/false 分配给 ConnectSocket。
使用
if ((ConnectSocket = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol)) == INVALID_SOCKET)
查看 C++ 运算符优先级列表
关于c++ - winsock 连接方法错误 10038,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070609/